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

Using InputStream.readAllBytes() Method

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 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 until all remaining bytes have been read and end of the stream is detected, 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.

Using ByteArrayOutputStream Class

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 to 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 an `ByteArrayOutputStream` isstance
    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();
}

Using BufferedReader Class

Another way of converting an InputStream object to a string is by wrapping it into a BufferedReader. You can then read it into a string just 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();
}

Using Scanner Class

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 scanner object
    Scanner scanner = new Scanner(stream).useDelimiter("\\A");

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

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

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

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.gralde file:

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

Further Reading

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

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5).