Avatar ·

How to convert InputStream to byte[] array in Java? All ways

Hello everyone! I'm new to Java and ran into this problem: I need to read all data from an InputStream (for example, from a file or from an HTTP response) and get it as a byte[] array. But I don't know how to do it correctly.

\n\n

Here's what I tried:

\n\n
InputStream input = new FileInputStream("data.bin");\nbyte[] data = ??? // How to get the byte array?\n
\n\n

The problem is that InputStream doesn't let me know the data size in advance. The available() method returns not the full size, but only what is already available for reading without blocking. I tried reading in a loop, but the code turns out messy and often breaks.

\n\n

I read about ByteArrayOutputStream, but I don't understand how to use it correctly. I also heard about readAllBytes()