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) {
// ???
}
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:
IOUtils.toString
(Apache Utils)CharStreams
(Guava)Scanner
(JDK)\r\n
) to\n
.\r\n
) to\n
.InputStreamReader
andStringBuilder
(JDK)StringWriter
andIOUtils.copy
(Apache Commons)ByteArrayOutputStream
andinputStream.read
(JDK)BufferedReader
(JDK). Warning: This solution converts different line breaks (like\n\r
) toline.separator
system property (for example, in Windows to “\r\n”).BufferedInputStream
andByteArrayOutputStream
(JDK)inputStream.read()
andStringBuilder
(JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)Warning:
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: