Java Program to Convert InputStream to String

Java Programming Java8Object Oriented Programming

Following is an example Java program to Convert InputStream to String. Here we are trying to convert the contents of ByteArrayInputStream to string.

Example

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Scanner;

public class InputStreamToString {
   public static void main(String args[]) throws Exception{
      System.out.println("Enter a string ::");
      Scanner sc = new Scanner(System.in);
      byte[] data = sc.next().getBytes();
      int size = data.length;
      byte[] b = new byte[size];
      InputStream Inputstream = new ByteArrayInputStream(data);
      Inputstream.read(b);
      String str = new String(b);
      System.out.println(str);
   }
}

Output

Enter a string ::
Tutorialspoint
Tutorialspoint
raja
Published on 26-Apr-2018 12:29:35
Advertisements