If you have a java.io.InputStream
object, how should you process that object and produce a String
?
Suppose I have an InputStream
that contains text data, and I want to convert it to a String
, so for example I can write that to a log file.
What is the easiest way to take the InputStream
and convert it to a String
?
public String convertStreamToString(InputStream is) {
// ???
}
Best Answer
To summarize the other answers, I found 11 main ways to do this (see below). And I wrote some performance tests (see results below):
Ways to convert an InputStream to a String:
Using
IOUtils.toString
(Apache Utils)Using
CharStreams
(Guava)Using
Scanner
(JDK)Using Stream API (Java 8). Warning: This solution converts different line breaks (like
\r\n
) to\n
.Using parallel Stream API (Java 8). Warning: This solution converts different line breaks (like
\r\n
) to\n
.Using
InputStreamReader
andStringBuilder
(JDK)Using
StringWriter
andIOUtils.copy
(Apache Commons)Using
ByteArrayOutputStream
andinputStream.read
(JDK)Using
BufferedReader
(JDK). Warning: This solution converts different line breaks (like\n\r
) toline.separator
system property (for example, in Windows to "\r\n").Using
BufferedInputStream
andByteArrayOutputStream
(JDK)Using
inputStream.read()
andStringBuilder
(JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)Warning:
Solutions 4, 5 and 9 convert different line breaks to one.
Solution 11 can't work correctly with Unicode text
Performance tests
Performance tests for small
String
(length = 175), url in github (mode = Average Time, system = Linux, score 1,343 is the best):Performance tests for big
String
(length = 50100), url in github (mode = Average Time, system = Linux, score 200,715 is the best):Graphs (performance tests depending on Input Stream length in Windows 7 system)
Performance test (Average Time) depending on Input Stream length in Windows 7 system: