Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Slurp InputStream to String (See related posts)

   1  
   2  public static String slurp (InputStream in) throws IOException {
   3      StringBuffer out = new StringBuffer();
   4      byte[] b = new byte[4096];
   5      for (int n; (n = in.read(b)) != -1;) {
   6          out.append(new String(b, 0, n));
   7      }
   8      return out.toString();
   9  }

Comments on this post

Talchas posts on Feb 22, 2006 at 19:28
Of course, in 1.5 you would want to use StringBuilder.
philemine posts on Aug 08, 2006 at 11:40
Other way to do this:
public static String inputStreamAsString(InputStream stream)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;

while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}

br.close();
return sb.toString();
}
The_Farwall posts on Sep 27, 2006 at 13:07
What's the significance of setting the byte array size to 4096, how was that determined/decided on?
Perlyking posts on Oct 26, 2006 at 12:21
One possible problem with the StringBuilder code above is that a "\n" is automatically appended to the end of the string, even if the original file on disk did not end with a newline. Your string may thus not be an accurate representation of the file.

You need to create an account or log in to post comments to this site.


Click here to browse all 5551 code snippets

Related Posts