In this tutorial, I will guide you to convert from InputStream to ByteArray using Apache Commons IO library.
In the Apache Commons IO library, there is a class called IOUtils. It contains three methods that allow us to easily convert from InputStream to ByteArray. That is:
1 |
IOUtils.toByteArray(InputStream is); |
This method is used in case you do not know the size of the file but knows its InputStream.
1 |
IOUtils.toByteArray(InputStream is, int size); |
We will use this method when we know the size of the file, of course, the InputStream of that file.
1 |
IOUtils.toByteArray(InputStream is, long size); |
This method is similar to the second method we mentioned here, but instead of the size of the file is calculated by int, we will calculate by long.
In the third method itself, it also calls the second method. Here is its code:
1 2 3 4 5 6 7 |
public static byte[] toByteArray(InputStream input, long size) throws IOException { if (size > Integer.MAX_VALUE) { throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size); } return toByteArray(input, (int) size); } |
OK, now let’s try to use the first two methods to convert the InputStream of a file to a ByteArray.
The first method:
1 2 3 4 5 |
File file = new File("F:\\HOC-TIENG-ANH-BANG-HINH-HOCHOC.COM.zip"); InputStream is = new FileInputStream(file); long start = System.currentTimeMillis(); IOUtils.toByteArray(is); System.err.println(System.currentTimeMillis() - start); |
Result:
1 |
629 |
Second method:
1 2 3 4 5 |
File file = new File("F:\\HOC-TIENG-ANH-BANG-HINH-HOCHOC.COM.zip"); InputStream is = new FileInputStream(file); long start = System.currentTimeMillis(); IOUtils.toByteArray(is, file.length()); System.err.println(System.currentTimeMillis() - start); |
Result:
1 |
392 |
Obviously, looking at the execution time of the two methods above, I think we should use the second method, do not you?