Convert InputStream to ByteArray using Apache Commons IO

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:

This method is used in case you do not know the size of the file but knows its InputStream.

We will use this method when we know the size of the file, of course, the InputStream of that file.

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:

OK, now let’s try to use the first two methods to convert the InputStream of a file to a ByteArray.

The first method:

Result:

Second method:

Result:

Obviously, looking at the execution time of the two methods above, I think we should use the second method, do not you?


Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment