Java Program to Convert InputStream to String
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:
- Using InputStreamReader class
- Using BufferedReader Class
- 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.
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.
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.
Please Login to comment...