Could someone tell me what happens in this method?

Asked

Viewed 244 times

2

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

 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();

  }

1 answer

7


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

The ByteArrayOutputStream is a stream output that keeps everything you write (write) in remembrance.

The code is basically reading the contents of InputStream in blocks up to 1KiB (1024 bytes) and writing it to 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 alternative implementations to solve this problem. Java 9 will include a new method InputStream.readAllBytes() for that purpose.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.