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\nHere's what I tried:
\n\nInputStream input = new FileInputStream("data.bin");\nbyte[] data = ??? // How to get the byte array?\n\n\nThe 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.
I read about ByteArrayOutputStream, but I don't understand how to use it correctly. I also heard about readAllBytes()
No answers yet.
Log in to leave an answer
Blogs