snippetjavaCritical
How do I read / convert an InputStream into a String in Java?
Viewed 0 times
howinputstreamjavaconvertstringintoread
Problem
If you have a
Suppose I have an
What is the easiest way to take the
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) {
// ???
}Solution
A nice way to do this is using Apache Commons
or even
Alternatively, you could use
IOUtils to copy the InputStream into a StringWriter... Something likeStringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();or even
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);Alternatively, you could use
ByteArrayOutputStream if you don't want to mix your Streams and Writers.Code Snippets
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);Context
Stack Overflow Q#309424, score: 2762
Revisions (0)
No revisions yet.