If I start with a java.io.InputStream, what's the easiest way to read the entire stream out into a String (assuming utf-8)?
This should be pretty easy but I'm mostly a C# person and google is failing me on this. Thanks.
If I start with a java.io.InputStream, what's the easiest way to read the entire stream out into a String (assuming utf-8)?
This should be pretty easy but I'm mostly a C# person and google is failing me on this. Thanks.
Depending on what licenses you are comfortable with, it's a one liner with Jakarta-Commons IO library.
Do specify the character encoding. Do not waste code, introduce bugs, and slow execution with a BufferedReader
.
Here is an example. You could parameterize it with a buffer size, encoding, etc.
static String readString(InputStream is) throws IOException {
char[] buf = new char[2048];
Reader r = new InputStreamReader(is, "UTF-8");
StringBuilder s = new StringBuilder();
while (true) {
int n = r.read(buf);
if (n < 0)
break;
s.append(buf, 0, n);
}
return s.toString();
}
Reading/writing from streams is remarkably painful in Java.
public static String getStreamContents(InputStream stream) throws IOException {
StringBuilder content = new StringBuilder()
Reader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"))
String lineSeparator = System.getProperty("line.separator");
try {
String line
while ((line = reader.readLine()) != null) {
content.append(line + lineSeparator)
}
return content.toString()
} finally {
reader.close()
}
}
Using Commons-IO is likely to be the best option. For your interest, another approach is to copy all the bytes and then convert it into a String.
public static String readText(InputStream is, String charset) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
for(int len;(len = is.read(bytes))>0;)
baos.write(bytes, 0, len);
return new String(baos.toByteArray(), charset);
}
I've found a nice way in Java 8 with streams:
public static String readString(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String content = br.lines().reduce("", String::concat);
return content;
}
As stated above you can swap new InputStreamReader(is) with new InputStreamReader(is, "UTF-8"), but I have no experience with this constructor.