Not sure about how I am supposed to do this. Any help would be appreciated
Example 1: Java Program to Convert InputStream to Byte Arraybyte[] array = stream. readAllBytes(); Here, the readAllBytes() method returns all the data from the stream and stores in the byte array. Note: We have used the Arrays.
The IOUtils type has a static method to read an InputStream and return a byte[] . InputStream is; byte[] bytes = IOUtils. toByteArray(is); Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray() .
Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.
Read from input stream and write to a ByteArrayOutputStream, then call its toByteArray()
to obtain the byte array.
Create a ByteArrayInputStream around the byte array to read from it.
Here's a quick test:
import java.io.*; public class Test { public static void main(String[] arg) throws Throwable { File f = new File(arg[0]); InputStream in = new FileInputStream(f); byte[] buff = new byte[8000]; int bytesRead = 0; ByteArrayOutputStream bao = new ByteArrayOutputStream(); while((bytesRead = in.read(buff)) != -1) { bao.write(buff, 0, bytesRead); } byte[] data = bao.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(data); System.out.println(bin.available()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With