It's important to mention that lines() uses the readLine() method under the hood. readLine() assumes that a line is terminated by any one of a line feed (“\n”), a carriage return (“\r”), or a carriage return followed immediately by a linefeed. In other words, it supports all the common End Of Line styles – Unix, Windows, and even old Mac OS.

On the other hand, when we use Collectors.joining(), we need to explicitly decide which type of EOL we want to use for the created String.

We could also use the Collectors.joining(System.lineSeparator()), in which case the output depends on the system settings.

5. Converting With Java and a Scanner

Next – let's look at a plain Java example – using a standard text Scanner:

In this example, first, the InputStream is converted to a ByteArrayOutputStream by reading and writing byte blocks, then the OutputStream is transformed to a byte array, which is used to create a String.

7. Converting With java.nio

Another solution is to copy the content of the InputStream to a file, then convert this to a String:

Here, we're using the java.nio.file.Files class to create a temporary file, as well as copy the content of the InputStream to the file. Then, the same class is used to convert the file content to a String with the readAllBytes() method.

8. Conclusion

After compiling the best way to do the simple conversion – InputStream to String – in a correct and readable way – and after seeing so many wildly different answers and solutions – I think that a clear and concise best practice for this is called for.

The implementation of all these examples and code snippets can be found on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

@baeldung:disqus All the examples are very good. I am usually in favor of code that relies as much as possible on functionalities coming straight from the Java standard library. Pointing out about try-with-resources is also nice. I don’t think that many developers are fully aware of it, and perhaps, it’s worth giving it attention in another “back to basics” post. Keep up the good work!