Adam Bien's Weblog

Reading InputStream Into String With Java 8

    public static String read(InputStream input) throws IOException {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
            return buffer.lines().collect(Collectors.joining("\n"));

See also: "Reducing a list into a csv string"

NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices


A book about rethinking Java EE Patterns


Nice piece of code. I would add that it's better to instantiate the InputStreamReader with an explicit charset instead of relying on the JVM default, which might not be the one you want.

E.g.: new InputStreamReader(input, StandardCharsets.UTF_8);

Posted by Diego Giagio on October 19, 2015 at 04:54 AM CEST #

Why not just use a Scanner instead?

return new Scanner(input, "utf-8").useDelimiter("\\Z").next();

Seems a shame to parse out the lines of the input only to immediately join them back together again.

Posted by Miles on October 19, 2015 at 05:12 PM CEST #

Awesome! I'd change "\n" with System.lineSeparator() for better reading purposes

Posted by George Gastaldi on January 20, 2017 at 12:32 PM CET #

This code skip the last '\n' of the stream if any

Posted by Riccardo Casatta on March 04, 2017 at 12:28 PM CET #

System.lineSeparator() has bitten me several times. Only use it when you *know* the content won't cross between windows/and Unix worlds, otherwise it creates a weird nearly invisible bug that depends on the platform.

Posted by Frank on March 17, 2017 at 12:06 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments