In this article, you'll learn how to convert an InputStream object to a String in Java using different Java APIs and a 3rd-party library — Apache Commons IO.

Convert an InputStream to a string using InputStream.readAllBytes()

Since Java 9, you can use the readAllBytes() method from InputStream to read all bytes into a byte array, as shown below:

try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) {
    // convert stream to a string
    String contents = new String(stream.readAllBytes(), StandardCharsets.UTF_8);

    // print string
    System.out.println(contents);

} catch (IOException ex) {
    ex.printStackTrace();
}

This method reads all bytes from the InputStream object at once. It blocks the execution until all remaining bytes have been read or an exception is thrown.

The reallAllBytes() method does not automatically close the InputStream instance. When this stream reaches the end of the stream, further invocations of this method will return an empty byte array.

You should use this method for simple use cases where it is convenient to read all bytes into a byte array. It is not intended for reading input streams with large amounts of data.

Convert an InputStream to a string using ByteArrayOutputStream

The ByteArrayOutputStream class implements an output stream in which the data is written into a byte array buffer. This buffer automatically grows as soon as more data is written into it.

You can read a chunk of input stream data and then write it into ByteArrayOutputStream as shown below:

try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) {
    // create a `ByteArrayOutputStream` instance
    ByteArrayOutputStream bais = new ByteArrayOutputStream();

    // read data from input stream
    byte[] buffer = new byte[1024];
    int length;
    while ((length = stream.read(buffer)) != -1) {
        bais.write(buffer, 0, length);
    }

    // convert bytes stream to string
    String contents = bais.toString(StandardCharsets.UTF_8.name());

    // print string
    System.out.println(contents);

} catch (IOException ex) {
    ex.printStackTrace();
}

Convert an InputStream to a string using BufferedReader

Another way of converting an InputStream object to a string is by wrapping it into a BufferedReader object. You can then read it into a string or a text file. Here is an example:

try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) {
    // convert stream into a reader
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

    // read all lines
    String contents = reader.lines().collect(Collectors.joining("\n"));

    // print string
    System.out.println(contents);

} catch (IOException ex) {
    ex.printStackTrace();
}

Convert an InputStream to a string using Scanner

You can use the Scanner class as well for converting an instance of InputStream to a string, as shown below:

try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) {
   // create a scanner object
    Scanner scanner = new Scanner(stream).useDelimiter("\\A");

    // read data from the scanner
    StringBuilder builder = new StringBuilder();
    while (scanner.hasNext()) {
        builder.append(scanner.next());
    }

    // print string
    System.out.println(builder.toString());

} catch (IOException ex) {
    ex.printStackTrace();
}

Convert an InputStream to a string using Apache Commons IO

The Apache Commons IO library provides the IOUtils.copy() method to copy the InputStream object into a StringWriter. You can then use StringWriter to convert it into a string, as shown below:

try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) {
    // create string writer
    StringWriter writer = new StringWriter();

    // copy input stream to writer
    IOUtils.copy(stream, writer, StandardCharsets.UTF_8);

    // convert to string
    System.out.println(writer.toString());

} catch (IOException ex) {
    ex.printStackTrace();
}

Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml file:

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

For a Gradle project, add the following dependency to your build.gradle file:

implementation 'commons-io:commons-io:2.6'

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.