Java Text File Read by Charset readAsString(InputStream in, Charset charset)

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

Description

read As String

License

Apache License

Declaration

public static String readAsString(InputStream in, Charset charset) throws IOException 

Method Source Code


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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class Main {
    private static final int BUFFER_SIZE = 4096;

    public static String readAsString(InputStream in) throws IOException {
        return new String(readAsBytes(in));
    }/*from  w  ww .  j a v  a2  s  . co m*/

    public static String readAsString(InputStream in, long length) throws IOException {
        return new String(readAsBytes(in, length));
    }

    public static String readAsString(InputStream in, Charset charset) throws IOException {
        return new String(readAsBytes(in), charset);
    }

    public static String readAsString(InputStream in, long length, Charset charset) throws IOException {
        return new String(readAsBytes(in, length), charset);
    }

    public static byte[] readAsBytes(InputStream in, long maxSize) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            int byteCount = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = 0;

            while ((byteCount < maxSize) && (bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
                byteCount += bytesRead;
            }
            out.flush();
            return out.toByteArray();
        } finally {
            try {
                if (null != in)
                    in.close();
            } catch (IOException ex) {
            }
            try {
                if (null != out)
                    out.close();
            } catch (IOException ex) {
            }
        }
    }

    public static byte[] readAsBytes(InputStream in) throws IOException {
        return readAsBytes(in, Long.MAX_VALUE);
    }
}

Related

  1. readAllLines(File file, Charset cs, String newLineDelimiter)
  2. readAllLines(InputStream stream, Charset charset)
  3. readAllLines(Path path, Charset cs)
  4. readAllText(File file, Charset charset)
  5. readAllText(File file, Charset charset)
  6. readAsString(InputStream is, CharsetDecoder decoder)
  7. readCharsWithEncoding(File file, Charset charset)
  8. reader(Class baseClass, String resourceName, Charset charset)
  9. reader(InputStream in, String charsetName)