How to convert InputStream to byte array in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 09-Jan-2018 10:11:16
Advertisements