Friday, April 19, 2013

How to Convert InputStream to Byte Array in Java - 2 Examples

Sometimes we need to convert InputStream to byte array in Java, or you can say reading InputStream as byte array, In order to pass output to a method which accept byte array rather than InputStream. One popular example of this, I have seen is older version of Apache commons codec, while converting byte array to hex string. Though, later version of same library do provide an overloaded method, to accept InputStream. Java File API provides excellent support to read files like image, text as InputStream in Java program, but as I said, sometime you need  need String or byte array, instead of InputStream . Earlier we have seen 5 ways to convert InputStream to String in Java , we can use some of the techniques from there while getting byte array from InputStream in Java. If you like to use Apache commons library, which I think you should, there is a utility class called IOUtils, which can be used to easily convert InputStream to byte array in Java. If you don't like using open source library for such kind of thinks, and like to write your own method, you can easily do so by using standard Java File API. In this Java tutorial we will see examples of both ways to convert InputStream to byte array in Java.


Java program to convert InputStream to byte array in Java

Here is complete code example of reading InputStream as byte array in Java. This Java program has two methods, one uses Apache commons IOUtils library to convert InputStream as byte array, while other uses core Java class methods. If you look at Apache commons code, it's just a one liner and it's tested for various kind of input e.g. text file, binary file, images, and both large and small files. By writing your own method for common utilities, which is good in sense of ownership; It's difficult to get same kind of testing exposure. That's the reason I prefer to use open source libraries, like Apache commons and Google Guava, along with JDK. They effectively complement standard Java library, and with Maven, it’s pretty easy to manage dependency. By the way, In this example, we are reading a small text file using FileInputStream in Java.

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

/**
 * Java program to convert InputStream to byte array in Java.
 * This Java examples uses Apache commons IOUtils to 
 * create byte array from InputStream
 * and Simply Java method to convert InputStream to byte array.
 *
 * @author Javin Paul
 */
public class InputStreamToByteArray {
 
    public static void main(String args[]) throws FileNotFoundException, IOException {
       
        //Converting InputStream to byte array using apche commons IO library
        int length = toByteArrayUsingCommons(
                       new FileInputStream("C:/temp/abc.txt")).length;
        
        System.out.println("Length of byte array created from InputStream in Java using IOUtils : " + length);
       
       
        //Converting InputStream to Byte arrray using Java code
        length = toByteArrayUsingJava(
                    new FileInputStream("C:/temp/abc.txt")).length;
        System.out.println("Length of Byte array created from FileInputStream in Java           : " + length);
       
    } 
   
  
    /*
     * Converts InputStream to ByteArray in Java using Apache commons IOUtils class
     */
    public static byte[] toByteArrayUsingCommons(InputStream is)
    throws IOException{
        return IOUtils.toByteArray(is);
    }
   
    /*
     * Read bytes from inputStream and writes to OutputStream,
     * later converts OutputStream to byte array in Java.
     */
    public static byte[] toByteArrayUsingJava(InputStream is)
    throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int reads = is.read();
       
        while(reads != -1){
            baos.write(reads);
            reads = is.read();
        }
      
        return baos.toByteArray();
       
    }
}

Output:
Length of byte array created from InputStream in Java using IOUtils :
27
Length of Byte array created from FileInputStream in Java           :
27 

That's all on How to convert InputStream to byte array in Java. You can this trick to get byte array from any kind of InputStream e.g. ObjectInputStream, FileInputStream or DataInputStream in Java.


No comments :

Post a Comment