Wednesday, May 25, 2016

Convert InputStream to String in Java

Sometimes in Java world it is necessary to convert an InputStream to a String for further processing. There are several ways to do it, but here is a fantastic trick I recently discovered in this article:
final String text = new Scanner(inputStream)
The idea behind this trick is regex \A. It matches the beginning of input. Since there is only one beginning of input the whole contents of the stream is returned as the first (and the last) token.

There is a problem with the code above. It would throw an exception if the provided stream is empty. However this is easy to fix:
final Scanner scanner = new Scanner(inputStream)
final String text = scanner.hasNext() ? : "";
If a specific charset must be used it could be passed as the second argument to the Scanner constructor:
final Scanner scanner = new Scanner(inputStream, "ISO-8859-1")
final String text = scanner.hasNext() ? : "";
That's all there is to it.
Thanks for reading!