Convert InputStream to String

In Java it’s quite common situation that you’re getting a InputStream class and you want to convert it to a String instance. Luckily with the java.util.Scanner class this can be achieved quite easily. The following code snippet shows how it’s done:

private String convertInputStream(InputStream is, String encoding) {
    Scanner scanner = new Scanner(is, encoding).useDelimiter("\\A");
    return scanner.hasNext() ? scanner.next() : "";
}

The Scanner class is constructed with the InputStream instance and the encoding info. The useDelimeter method sets the delimeter as the beginning of the input and the last row makes sure that an empty String is returned if the InputStream is empty.

It’s easy as that!

Further reading

Comments

comments powered by Disqus