Monday, November 27, 2006

Snippet://Java/InputStream

Java code snippet to read InputStream using buffered reader.

NOTE: StringBuffer won't insert extra \n, so the returned string will be exactly as the InputStream. Also, the unusual for statement in the snippet below is 10 times faster than the traditional while statement.

private static String slurp(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}

No comments: