How to convert InputStream to String in Java?

We have different  ways to convert InputStream to String as given below.

  1. Using BufferedReader and InputStreamReader

  2. Using ByteArrayOutputStream and InputStream read

  3. Using ByteArrayOutputStream and BufferedInputStream

  4. Using Scanner class

  5. Using Apache Commons IOUtils toString

  6. Using Java 8 Streams

 

1) Using BufferedReader and InputStreamReader

Create BufferedReader object  from InputStream using InputStreamReader. It will read the content line by line from BufferedReader and append the lines to StringBuilder. Once done, convert StringBuilder to String using toString method.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class InputStreamToString {
  public static void main(String[] args) {
       InputStream is = null;
       try{
            File f=new File("E:/java/text.txt");
            System.out.println("File exist "+f.exists());
            //create InputStream from file
            is = new FileInputStream(f);
         String str = convertInputStreamToString(is);
            System.out.println(str);
       }catch(IOException ioe){
            ioe.printStackTrace();
        }finally{            
            try{
                if(is != null)
                    is.close();
            }catch(Exception e){ e.printStackTrace();  }
        }
    }
    
    /*
     * Method to convert InputStream to String
     */
    private static String convertInputStreamToString(InputStream is) {
        BufferedReader br = null;
        StringBuilder sbContent = new StringBuilder();
      try{
            /*
             * Create BufferedReader from InputStreamReader 
             */
            br = new BufferedReader(new InputStreamReader(is));
         /*
             * read line by line and append content to
             * StringBuilder
             */
            String strLine = null;
            boolean isFirstLine = true;
           while( (strLine = br.readLine()) != null){
                if(isFirstLine)
                    sbContent.append(strLine);
                else
                    sbContent.append("\n").append(strLine);
               /*
                 * Flag to make sure we don't append new line
                 * before the first line. 
                 */
                isFirstLine = false;
            }
        }catch(IOException ioe){
            ioe.printStackTrace();
        }finally{            
            try{
                if(br  != null)
                    br.close();
            }catch(Exception e){ e.printStackTrace();  }
        }
        //convert StringBuilder to String and return
        return sbContent.toString();
    }
}

 

Output

Welcome to Java File to String
This Example shows Convert to String

 

2) Using ByteArrayOutputStream and InputStream read

private static String convertInputStreamToString(InputStream is) {
        
       String strResult = null;
    
    //create ByteArrayOutputStream
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
    try{
        
        //create buffer to hold bytes read from stream
        byte[] buffer = new byte[1024];
        
        /*
         * Read bytes from InputStream to buffer
         * until there are no more bytes 
         */
        int size;
        while((size = is.read(buffer)) != -1){
            
            //write buffer to the ByteArrayOutputStream
            bos.write(buffer, 0, size);
        }
        
        //convert ByteArrayOutputStream to String using UTF-8 Character Set
        strResult = bos.toString( StandardCharsets.UTF_8.name());
        
    }catch(IOException ioe){
        ioe.printStackTrace();
    }finally{            
        try{
            if(bos != null)
                bos.close();
        }catch(Exception e){ e.printStackTrace();  }
    }
    
    return strResult;
    }
    

 

3) Using ByteArrayOutputStream and BufferedInputStream

 private static String convertInputStreamToString(InputStream is) {
        
      String strResult = null;
    
    ByteArrayOutputStream bos = null;
    BufferedInputStream bis = null;
    
    try{
        
        //create ByteArrayOutputStream
        bos = new ByteArrayOutputStream();
        
        //create BufferedInputStream from InputStream
        bis = new BufferedInputStream(is);
        
        int byteValue;
        while( (byteValue = bis.read()) != -1 ){
            bos.write(byteValue);
        }
        
        //convert ByteArrayOutputStream to String using UTF-8 Character Set
        strResult = bos.toString( StandardCharsets.UTF_8.name());
        
    }catch(IOException ioe){
        ioe.printStackTrace();
    }finally{            
        try{
            if(bos != null)
                bos.close();
        }catch(Exception e){ e.printStackTrace();  }
        try{
            if(bis != null)
                bis.close();
        }catch(Exception e){ e.printStackTrace();  }
    }
    
    return strResult;
    }

 

4) Using Scanner

 private static String convertInputStreamToString(InputStream is) {
        
     String strResult = null;
    
    Scanner scanner = null;
    
    try{
        
        //create scanner from InputStream
        scanner = new Scanner(is);
        
        //set scanner delimiter as beginning of the content
        scanner.useDelimiter("\\A");
        
        //get the token - this will return whole content as single token
        if( scanner.hasNext() )
            strResult = scanner.next();
        
    }catch(Exception e){
        e.printStackTrace();
    }finally{            
        try{
            if(scanner != null)
                scanner.close();
        }catch(Exception e){ e.printStackTrace();  }
    }
    
    return strResult;
    }

 

5) Using Apache Commons IOUtils toString

private static String convertInputStreamToString(InputStream is) throws IOException {

    

    String strResult = IOUtils.toString(is, Charset.forName("UTF-8"));    

    return strResult;

}

 

6) Using Java 8 Streams

private static String convertInputStreamToString(InputStream is) throws IOException {

    

    //Create BufferedReader from the input stream

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    

    //read lines separated by new line and join them again using \n

    String strResult = br.lines().collect(Collectors.joining("\n"));

    

    return null;

}

 


Subscribe For Daily Updates

JAVA File IO examples

JAVA Date & Time Progamming Examples

JAVA Collections

Flutter Questions
Android Questions