Java - Write code to Convert an Input Stream to a String

Requirements

Write code to Convert an Input Stream to a String

Demo

//package com.book2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {
    /**//from  w  ww.  j  a  v  a 2 s  .c om
     * Converts an Input Stream to a String
     *
     * @param stream
     * @return
     * @throws java.io.IOException
     */
    public static String inputStreamToString(InputStream stream)
            throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                stream));
        StringBuilder builder = new StringBuilder();

        String line = null;

        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append("\n");
        }

        reader.close();
        stream.close();

        return builder.toString();

    }
}

Related Exercise