DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Slurp InputStream To String

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


Carla Brian replied on Wed, 2012/07/18 - 9:21am

This code will be really helpful. I don't know about strings. It is so hard to practice . I need more tutorials on this one. - Mercy Ministries

Bernd Juenger replied on Sun, 2007/06/17 - 11:16am

In addition to Perlyking really good point ... why would you create another string, when you have a StringBuilder!?! sb.append(line).append("\n");

Snippets Manager replied on Thu, 2006/10/26 - 12:08pm

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.

Snippets Manager replied on Wed, 2006/09/27 - 1:06pm

What's the significance of setting the byte array size to 4096, how was that determined/decided on?

Filip Krikava replied on Tue, 2006/08/08 - 11:36am

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(); }

Snippets Manager replied on Wed, 2006/02/22 - 8:28pm

Of course, in 1.5 you would want to use StringBuilder.