Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to read / convert an InputStream into a String in Java?

If a java.io.InputStream object is present , how should you process that object and produce a String?

Suppose an InputStream that contains text data, and I want to convert it to a String, so for example
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) {
// ???
}
by

2 Answers

sandhya6gczb
To copy input stream to string use Apache commons IOUtils.

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
espadacoder11
If you are using Google-Collections/Guava you could do the following:

InputStream stream = ...
String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
Closeables.closeQuietly(stream);

Note that the second parameter (i.e. Charsets.UTF_8) for the InputStreamReader isn't necessary, but it is generally a good idea to specify the encoding if you know it (which you should!)

Login / Signup to Answer the Question.