How to convert InputStream to String in Java

In Java, you can use BufferedReader + InputStreamReader to convert InputStream to String.

InputStreamToStringExample.java
package com.mkyong.core;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class InputStreamToStringExample {
 
	public static void main(String[] args) throws IOException {
 
		// intilize an InputStream
		InputStream is = 
                     new ByteArrayInputStream("file content..blah blah".getBytes());
 
		String result = getStringFromInputStream(is);
 
		System.out.println(result);
		System.out.println("Done");
 
	}
 
	// convert InputStream to String
	private static String getStringFromInputStream(InputStream is) {
 
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
 
		String line;
		try {
 
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
 
		return sb.toString();
 
	}
 
}

Output

file content..blah blah
Done
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: alkaline water brands()

  • Pingback: pay day loans()

  • Pingback: water ionizer loans()

  • Pingback: stop parking()

  • Pingback: laan penge nu uden sikkerhed()

  • Pingback: water ionizer machines()

  • Pingback: fue.mobi()

  • Pingback: laan her og nu()

  • Pingback: stop parking()

  • Pingback: tvpackages.net()

  • Pingback: kangen()

  • Pingback: kangen water()

  • Pingback: alkaline water()

  • Pingback: water ionizer()

  • Pingback: watch movies online free()

  • Pingback: streaming movies()

  • Pingback: watch free movies online()

  • Pingback: watch movies online()

  • Pingback: Blue Coaster33()

  • Umair Aslam

    Is vice-versa possible i.e to write a String to InputStream in Java?

  • Guy

    Are you sure using “sb.append(line);” won’t loose the “\n” at the end of each line?
    According to the JDoc of br.readLine():
    ” * @return A String containing the contents of the line, not including
    * any line-termination characters,”

    • http://www.mkyong.com mkyong

      So, did you lose the “\n” ?

      • Guy

        Or \r or both, the thing is you can’t just re-add them back, cause the readLine looses them.

      • Oleg

        Yes, I lost the ā€œ\nā€.

  • Bhushan

    It can easily done in 3 lines by using Guava library as shown in 5 ways to convert InputStream to String in Java

  • http://cloudcomputingglobe.com Cloud Computing

    Good tutorial

  • http://recipescookbook.org Mirta – Recipes Cookbook

    Why don’t you better use the Java Standard support for the translation? I personally avoid Scanners when possible.

        public String inputStram2String(InputStream in) throws IOException {
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            for (int i; (i = in.read(b)) != -1;) {
                out.append(new String(b, 0, i));
            }
            return out.toString();
        }
  • Max

    There’s a much better trick that doesn’t require apache stuff.

     String str = new Scanner(inputStream).useDelimiter("\\A").next();

    Essentially this tells the scanner to tokenize the stream until the end is reached, so next() returns the whole stream as a string.

  • Edward

    I prefer to use IOUtils.toString(InputStream) from Apache Commons.