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

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

Description

Reads contents of the input stream fully and returns it as String.

License

LGPL

Parameter

Parameter Description
in InputStream to read from.
charset name of supported charset to use

Exception

Parameter Description
IOException in case of IO error
IllegalArgumentException if stream is null

Return

contents of the input stream fully as String.

Declaration

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

Method Source Code

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

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

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    /**/* www .j  a  v a 2s .  c  o  m*/
     * Reads contents of the input stream fully and returns it as String. Sets UTF-8 encoding internally.
     *
     * @param in InputStream to read from.
     * @return contents of the input stream fully as String.
     * @throws IOException in case of IO error
     * @throws IllegalArgumentException if stream is null
     */
    public static String read(InputStream in) throws IOException {
        return read(in, StandardCharsets.UTF_8);
    }

    /**
     * Reads contents of the input stream fully and returns it as String.
     *
     * @param in InputStream to read from.
     * @param charset name of supported charset to use
     * @return contents of the input stream fully as String.
     * @throws IOException in case of IO error
     * @throws IllegalArgumentException if stream is null
     */
    public static String read(InputStream in, Charset charset) throws IOException {
        if (in == null)
            throw new IllegalArgumentException("input stream cannot be null");

        InputStreamReader reader = new InputStreamReader(in, charset);
        char[] buffer = new char[1024];
        StringBuilder sb = new StringBuilder();

        for (int x = reader.read(buffer); x != -1; x = reader.read(buffer)) {
            sb.append(buffer, 0, x);
        }
        return sb.toString();
    }
}

Related

  1. newReader(ReadableByteChannel ch, Charset cs)
  2. newUTF8CharSetReader(String filename)
  3. openNewCompressedInputReader(final InputStream inputStream, final Charset charset)
  4. read(File file, Charset charset)
  5. read(InputStream _is, CharsetDecoder _decoder)
  6. read(InputStream in, Charset cs, Appendable appendable, int capacity)
  7. read(InputStream in, String charsetName)
  8. readAll(InputStream in, Charset charset)
  9. readAll(InputStream inputStream, Charset charset)