Open In App

Java Program to Convert InputStream to String

Improve
Improve
Like Article
Like
Save
Share
Report

Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read data from files and FileOutputStream class is used to write data to files. There are several ways to convert an InputStream object to String in Java using inbuilt libraries as well as external libraries. 

Approaches: Three ways to convert InputStream object into String are:

  1. Using InputStreamReader class
  2. Using BufferedReader Class
  3. Using the Scanner class

Method 1: Using the InputStreamReader class

An InputStreamReader converts byte streams to character streams. It reads byte streams and decodes them into characters using the specified charset. If no charset is specified, it uses the default charset

In this method, the user-provided filename is passed as a parameter for file object initiation. This file object is again passed as a parameter for InputStream object initiation. The InputStreamReader object is initiated by passing the InputStream object. The InputStreamReader converts byte streams to character streams. The fetched character stream is stored in the character array using the read() method of InputStreamReader class. Finally, the character array is converted to String. 

Implementation: 

Java




import java.util.*;
import java.io.*;
public class InputStreamReaderDemo {
  
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the file path: ");
        String filename = s.nextLine();
        
        // Creating a File object
        File file = new File(filename);
        try {
            // Creating an InputStream object
            InputStream is = new FileInputStream(file);
            
            // creating an InputStreamReader object
            InputStreamReader isr = new InputStreamReader(is);
            
            // Creating a character array
            char charArray[] = new char[(int)file.length()];
            
            // Reading the contents of the reader
            isr.read(charArray);
            
            // Converting character array to a String
            String contents = new String(charArray);
            System.out.println(contents);
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
}


Output:

Method 2: Using BufferedReader class

The BufferedReader class is used to read the stream of characters from the input source (here file). The readLine() method of the BufferedReader class reads each line from the contents of the buffer reader object. 

In the example below, the user specifies the filename which is passed to the InputStream constructor for InputStream object initiation. The InputStream object is passed to the InputStreamReader constructor. The BufferedReader object is instantiated using the InputStreamReader object. A StringBuffer object is created which stores the lines read from the BufferedReader object. Finally, the contents of the StringBuffer object is converted to String.

Implementation:

Java




// Importing java libraries
import java.io.*;
import java.util.Scanner;
  
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the file path: ");
        String filename = s.nextLine();
        try {
            // Creating an InputStream object
            InputStream is = new FileInputStream(filename);
  
            // creating an InputStreamReader object
            InputStreamReader isr
                = new InputStreamReader(is);
  
            // Creating a BufferedReader object
            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
  
            String str;
  
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            System.out.println(sb.toString());
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
}


Output:

Method 3: Using the Scanner class

The Scanner class is used to read input from stdin. Scanner class has methods to accept input of primitive types like integer, double, float as well as String inputs. 

In the example below, the user specifies the filename which is passed to the InputStream constructor for FileInputStream object initiation. The FileInputStream object is then passed to the Scanner class constructor. The scanner object content is iterated and each line fetched is appended to the StringBuffer object. Finally, the StringBuffer content is converted to String and printed to the standard output.

Implementation:

Java




// Importing java libraries
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
  
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Taking input from the user
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the file path: ");
        String filename = s.nextLine();
        try {
  
            // Creating an InputStream object
            FileInputStream fis
                = new FileInputStream(filename);
  
            // Creating a Scanner object
            Scanner sc = new Scanner(fis);
  
            // Reading line by line from scanner to
            // StringBuffer
  
            StringBuffer sb = new StringBuffer();
            while (sc.hasNext()) {
                sb.append(sc.nextLine());
            }
  
            System.out.println(sb.toString());
        }
  
        // Catch block to handle exceptions
        catch (IOException e) {
            System.out.println(e);
        }
    }
}


Output



Last Updated : 02 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads