Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how can I convert an InputStream into a byte array (byte[])? [duplicate]

My background is .net, I'm fairly new to Java. I'm doing some work for our company's java team and the architect needs me to implement a method that takes an InputStream (java.io) object. In order to fulfill the method's purpose I need to convert that into a byte array. Is there an easy way to do this?

like image 295
Lee Warner Avatar asked Jan 29 '10 17:01

Lee Warner


People also ask

How do you convert input streams to bytes?

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.

How do you convert an InputStream to byteArray in java?

byte[] byteArray = IOUtils. toByteArray(inputStream);

Can we read InputStream twice in java?

You can check if mark() and reset() are supported using markSupported() . If it is, you can call reset() on the InputStream to return to the beginning. If not, you need to read the InputStream from the source again. InputStream doesn't support 'mark' - you can call mark on an IS but it does nothing.

How do you create a byte array in java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.


2 Answers

The simplest way is to create a new ByteArrayOutputStream, copy the bytes to that, and then call toByteArray:

public static byte[] readFully(InputStream input) throws IOException
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    return output.toByteArray();
}
like image 168
Jon Skeet Avatar answered Sep 20 '22 13:09

Jon Skeet


A simple way would be to use org.apache.commons.io.IOUtils.toByteArray( inputStream ), see apache commons io.

like image 34
tangens Avatar answered Sep 20 '22 13:09

tangens