Share

August 8, 2010

Java: Create a String from the InputStream

Small Until to create a String object from an InputStream
 
    /**
     * Creates a String from the stream
     * 
     * @param stream
     * @param addNewLine
     * @return the stream as string
     * @throws IOException
     */
    public static String asString(InputStream stream, boolean addNewLine) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(stream);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            if (addNewLine) {
                sb.append(IChar.NEW_LINE);
            }
        }
        return sb.toString();
    }