How to convert InputStream to String in Java
In Java, you can use BufferedReader + InputStreamReader to convert InputStream to String.
InputStreamToStringExample.java
package com.mkyong.core; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToStringExample { public static void main(String[] args) throws IOException { // intilize an InputStream InputStream is = new ByteArrayInputStream("file content..blah blah".getBytes()); String result = getStringFromInputStream(is); System.out.println(result); System.out.println("Done"); } // convert InputStream to String private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } }
Output
file content..blah blah
Done Tags : inputstream io java string

Is vice-versa possible i.e to write a String to InputStream in Java?
Are you sure using “sb.append(line);” won’t loose the “\n” at the end of each line?
According to the JDoc of br.readLine():
” * @return A String containing the contents of the line, not including
* any line-termination characters,”
So, did you lose the “\n” ?
Or \r or both, the thing is you can’t just re-add them back, cause the readLine looses them.
It can easily done in 3 lines by using Guava library as shown in 5 ways to convert InputStream to String in Java
Good tutorial
Why don’t you better use the Java Standard support for the translation? I personally avoid Scanners when possible.
There’s a much better trick that doesn’t require apache stuff.
Essentially this tells the scanner to tokenize the stream until the end is reached, so next() returns the whole stream as a string.
I prefer to use IOUtils.toString(InputStream) from Apache Commons.