First, the easiest way to write. Using Native Io, one byte reads one byte:
// One character to read, too slow int I; while (I = in. Read ())! =-1) {I = in. Read (); arr [J ++] = I ;}
This method is very slow and is not recommended.
Second, one read:
byte[] arr = new byte[in.available()];in.read(arr);
This is the opposite of the first one. When reading a stream at a time, this situation will occupy a lot of memory when the file is slightly larger, and is not recommended.
Third, buffer read:
byte[]buff = new byte[1024];int eachlength = 0;int total = 0;while((eachlength = in.read(buff)) != -1){ System.arraycopy(buff, 0, arr, total, eachlength); total += eachlength;}
In this way, 1024 bytes are read each time and then copied to the target array of arr.
Fourth, with commons-io:
org.apache.commons.io.IOUtils.toByteArray(input)
The implementation in the source code is:
public static byte[] toByteArray(InputStream input) throws IOException{ ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray();}public static int copy(InputStream input, OutputStream output) throws IOException{ long count = copyLarge(input, output); if (count > 2147483647L) { return -1; } return (int)count;}public static long copyLarge(InputStream input, OutputStream output) throws IOException{ byte[] buffer = new byte[4096]; long count = 0L; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count;}