Could anyone tell me what happens in this method?
I have a method that does a few things that I would like to know what it is...just explain it to me over the top, 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();
}
1 answers
The method in question is reading the entire contents of an input stream (e.g., from a file, network port, etc.) to an array of bytes in memory.
The ByteArrayOutputStream
is an output stream that keeps everything you write (write
) in memory.
The code is basicando by 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.
Fine line out.toByteArray()
returns everything that was written in ByteArrayOutputStream
as a byte[]
.
See that there are several alternative libraries and implementations to solve this problem. Java 9 inclusive will include a new method InputStream.readAllBytes()
for that purpose.