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 workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.


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 #

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