Java InputStream Read by Charset toString(InputStream in, Charset charset)

Here you can find the source of toString(InputStream in, Charset charset)

Description

to String

License

Apache License

Declaration

public static String toString(InputStream in, Charset charset) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.nio.charset.Charset;

public class Main {

    public static String toString(InputStream stream) {
        StringBuffer sb = new StringBuffer();
        byte[] buffer = new byte[1024];
        int length = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {/*  w w w  . j av  a 2s  .  c om*/
            while (-1 != (length = stream.read(buffer))) {
                baos.write(buffer, 0, length);
            }
            sb.append(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                stream.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static String toString(InputStream in, Charset charset) {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
        try {
            String str = null;
            while (null != (str = br.readLine())) {
                sb.append(str).append(System.getProperty("line.separator"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();

    }
}

Related

  1. toInputStream(String input, Charset charset)
  2. toInputStream(String input, Charset cs)
  3. toString(final InputStream input, final Charset encoding)
  4. toString(InputStream in, Charset charset)
  5. toString(InputStream in, Charset charset)
  6. toString(InputStream in, Charset charset)
  7. toString(InputStream in, Charset charset)
  8. toString(InputStream input, Charset charset)
  9. toString(InputStream input, String charset)