Skip to Content

Java InputStream to String Example

  1. import java.io.BufferedReader;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.Scanner;
  7.  
  8. /*
  9.         Java InputStream to String Example
  10.         This Java InputStream to String example shows how to convert InputStream to String in Java.
  11.  */
  12. public class ConvertInputStreamToStringExample {
  13.        
  14.         public static void main(String args[]) throws IOException{
  15.                
  16.                 //get InputStream of a file
  17.                 InputStream is = new FileInputStream("c:/data.txt");
  18.                 String strContent;
  19.                
  20.                 /*
  21.                  * There are several way to convert InputStream to String. First is using
  22.                  * BufferedReader as given below.
  23.                  */
  24.        
  25.                 //Create BufferedReader object
  26.                 BufferedReader bReader = new BufferedReader(new InputStreamReader(is));
  27.                 StringBuffer sbfFileContents = new StringBuffer();
  28.                 String line = null;
  29.                
  30.                 //read file line by line
  31.                 while( (line = bReader.readLine()) != null){
  32.                         sbfFileContents.append(line);
  33.                 }
  34.                
  35.                 //finally convert StringBuffer object to String!
  36.                 strContent = sbfFileContents.toString();
  37.                
  38.                 /*
  39.                  * Second and one liner approach is to use Scanner class. This is only supported
  40.                  * in Java 1.5 and higher version.
  41.                  */
  42.                
  43.                 strContent = new Scanner(is).useDelimiter("\\A").next();
  44.         }
  45. }