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"
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 #
If you're provided an InputStream, you shouldn't close it. The one that created the input stream should be responsible for that. Or you'll create a culture where people send streams left and right never closing them. Drop the try-with-resource and it's perfect! :D
Posted by Erik on August 19, 2018 at 12:45 PM CEST #