Suppose I have an InputStream
that contains text data, and I want to convert this to a String
(for example, so I can write the contents of the stre
You can use a BufferedReader
to read the stream into a StringBuilder
in a loop, and then get the full contents from the StringBuilder
:
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Full disclosure: This is a solution I found on KodeJava.org. I am posting it here for comments and critique.