Could anyone tell me what happens in this method?

2

I have a method that does some things that I would like to know what it is ... just explain me out loud please?

 private static byte[] readFully(InputStream in) throws IOException {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      for (int count; (count = in.read(buffer)) != -1; ) {
         out.write(buffer, 0, count);
      }
      return out.toByteArray();

  }
    
asked by anonymous 25.01.2017 / 15:32

1 answer

7

The method in question is reading the entire contents of an input stream (eg, from a file, network port, etc.) to an array of bytes in memory.

The ByteArrayOutputStream is an output that keeps everything you write ( write ) in memory.

The code is basic by reading the content of InputStream in blocks of up to 1KiB (1024 bytes) and writing it in ByteArrayOutputStream . This is a very manual way of buffering the operation.

Finely the line out.toByteArray() returns everything written in ByteArrayOutputStream as a byte[] .

See that there are several libraries and alternate implementations to solve this problem.

  • problem. Java 9 will include a new method InputStream.readAllBytes() for that purpose.

        
  • 25.01.2017 / 15:43