Read stream to String using encoding - Java java.io

Java examples for java.io:InputStream Read

Description

Read stream to String using encoding

Demo Code

//package com.java2s;
import java.io.*;

import java.nio.charset.Charset;

public class Main {
    private static final String LINE_SEPARATOR = System
            .getProperty("line.separator");

    public static String stream2String(InputStream is) {
        Charset charset = null;//from w  w w . j  av a  2s.  c om
        return stream2String(is, charset);
    }

    public static String stream2String(InputStream is, String charsetName) {
        Charset charset = !isEmpty(charsetName) ? Charset
                .forName(charsetName) : null;
        return stream2String(is, charset);
    }

    public static String stream2String(InputStream is, Charset charset) {
        if (is == null)
            return null;
        InputStreamReader isr = charset == null ? new InputStreamReader(is)
                : new InputStreamReader(is, charset);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        try {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append(LINE_SEPARATOR);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static boolean isEmpty(CharSequence s) {
        return s == null || s.length() == 0;
    }
}

Related Tutorials