How to convert an input stream to byte array in java?

Java Programming Java8Object Oriented Programming

The InputStream class in Java provides read() method. This method accepts a byte array and it reads the contents of the input stream to the given byte array.

Example

Live Demo

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamToByteArray {
    public static void main(String args[]) throws IOException{    
       InputStream is = new BufferedInputStream(System.in);
       byte [] byteArray = new byte[1024];
       System.out.println("Enter some data");
       is.read(byteArray);      
       String s = new String(byteArray);
       System.out.println("Contents of the byte stream are :: "+ s);
   }  
}

Output

Enter some data
hello how are you
Contents of the byte stream are :: hello how are you

Alternative Solution

Apache commons provides a library named org.apache.commons.io and, following is the maven dependency to add library to your project.

<dependency>
    <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
</dependency>

This package provides a class known as IOUtils. the toByteArray () method of this class accepts an InputStream object and returns the contents in the stream in the form of a byte array:

Example

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
public class StreamToByteArray2IOUtils {
   public static void main(String args[]) throws IOException{    
      File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte [] byteArray = IOUtils.toByteArray(fis);
      String s = new String(byteArray);
      System.out.println("Contents of the byte stream are :: "+ s);
   }  
}

Output

Contents of the byte stream are :: hello how are you
raja
Published on 23-Apr-2018 01:34:42
Advertisements