The Bad Programmer

Quick How-To: Convert InputStream to String



I find myself having to convert an InputStream to a String on occasion. It isn’t something I do super-frequently so I usually have to go hunt down some code where I have done it before. Here it is for quick reference for myself and whoever else. This code uses a Java 1.7 try-with-resources statement. If you aren’t using Java 1.7+ you will of course need to use the correct try syntax for prior versions of Java with a finally block.

 public String readBody(InputStream inputStream) throws Exception {
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        }
        return writer.toString();
    }