How do I read/convert an Input Stream into a String in Java?

Submitted 4 years, 2 months ago
Ticket #350
Views 345
Language/Framework Java
Priority Low
Status Closed

Please explain?

Submitted on Feb 11, 21
add a comment

1 Answer

Verified

There are two types of streams available in

  1. InputStream − This is used to read (sequential) data from a source.
  2. OutputStream − This is used to write data to a destination.

We can convert an InputStream Object int to a String in several ways using core Java. We can also use external libraries like IOUtils, Guava for this purpose. Following are some ways to convert an InputStream object to String in Java (not including external libraries).

Using the scanner class:

The nextLine() method of the Scanner class reads the contents of the underlying inputStream line by line. To convert an InputStream Object int to a String using this method.

  1. Instantiate the Scanner class by passing your InputStream object as parameter.
  2. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object.
  3. Finally convert the StringBuffer to String using the toString() method.

Using the InputStreamReader class:

The read() method of the InputStreamReader class accepts a character array as a parameter and reads the contents of the current Stream to the given array. To convert an InputStream Object int to a String using this method.

  1. Instantiate an InputStreamReader class by passing your InputStream object as parameter.
  2. Read the contents of the current stream reader to a character array using the read() method of the InputStreamReader class.
  3. Finally convert the character to a String by passing it as a parameter to its constructor.

Using BufferedReader:

The readLine() method of the BufferedReader class reads a single line from the contents of the current reader. To convert an InputStream Object int to a String using this method.

  1. Instantiate an InputStreamReader class by passing your InputStream object as parameter.
  2. Then, create a BufferedReader, by passing above obtained InputStreamReader object as a parameter.
  3. Now, read each line from this reader using the readLine() method and append it to a StringBuffer object.
  4. Finally convert the StringBuffer to String using the toString() method.

Submitted 4 years, 2 months ago


Latest Blogs