How to convert InputStream to String in Java

In Java, there are few ways to convert InputStream to String :

1. Pure Java – ByteArrayOutputStream


	private static String convertInputStreamToString(InputStream inputStream) 
		throws IOException {

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(StandardCharsets.UTF_8.name());

    }

2. If Java 9, try this inputStream.readAllBytes :


	private static String convertInputStreamToStringJDK9(InputStream inputStream) 
		throws IOException {
		
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
		
    }

3. Apache Commons IO – IOUtils.copy

pom.xml

	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.6</version>
	</dependency>

	private static String convertInputStreamToStringCommonIO(InputStream inputStream) 
		throws IOException {
		
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
        return writer.toString();
		
    }

1. Convert InputStream to String

InputStreamToString.java

package com.mkyong;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;

public class InputStreamToString {

    public static void main(String[] args) throws IOException {

        URI u = URI.create("https://www.google.com/");
        try (InputStream inputStream = u.toURL().openStream()) {

			// InputStream -> String
            String result = convertInputStreamToString(inputStream);
            System.out.println(result);

        }

    }

    // Pure Java
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(StandardCharsets.UTF_8.name());

    }

    // Since Java 9
    private static String convertInputStreamToStringJDK9(InputStream inputStream) throws IOException {
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }

    // commons-io
    private static String convertInputStreamToStringCommonIO(InputStream inputStream) throws IOException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
        return writer.toString();
    }

}

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
Max
Guest
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.

Umair Aslam
Guest
Umair Aslam

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

Abel Bottello
Guest
Abel Bottello

Thank you so much, finally I could print some text gotten from a GET request in Android…

Edward
Guest
Edward

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

Mirta - Recipes Cookbook
Guest
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(); }

Cloud Computing
Guest
Cloud Computing

Good tutorial

Bhushan
Guest
Bhushan

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

Guy
Guest
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,”

Mali
Guest
Mali

Thanks a lot !

Jonathan G Kline
Guest
Jonathan G Kline

In case you want to update and include a Java 8 version, this is your code but with a try-with-resources block instead of a try-catch-finally block:

try(BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)))
{
while((line = br.readLine()) != null)
{
sb.append(line);
}
} catch(IOException e)
{
e.printStackTrace();
}