Monday 22 April 2013

Convert InputStream to byte array in Java

Leave a Comment

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.

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; 
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 


0 comments:

Post a Comment