Java Text File Read by Charset readFromInputStream(InputStream stream, Charset charset)

Here you can find the source of readFromInputStream(InputStream stream, Charset charset)

Description

read From Input Stream

License

Creative Commons License

Declaration

public static String readFromInputStream(InputStream stream, Charset charset) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Creative Commons License 

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

import java.util.LinkedList;
import java.util.List;

public class Main {
    public static String readFromInputStream(InputStream stream, Charset charset) throws IOException {
        List<Byte> bytes = new LinkedList<>();
        byte[] buffer = new byte[128];
        int read;
        while ((read = stream.read(buffer)) != -1) {
            for (int i = 0; i < read; i++) {
                bytes.add(buffer[i]);//from   w  w w.  j  av  a2s.  co  m
            }
        }

        int total = bytes.size();
        buffer = new byte[total];
        for (int i = 0; i < total; i++) {
            buffer[i] = bytes.remove(0);
        }

        if (charset == null) {
            return new String(buffer);
        } else {
            return new String(buffer, charset);
        }
    }

    public static String readFromInputStream(InputStream stream) throws IOException {
        return readFromInputStream(stream, null);
    }
}

Related

  1. readFileContents(File file, Charset charset)
  2. readFileToLines(String inFile, String inCharset)
  3. readFileToList(String filePath, String charsetName)
  4. readFileToString(String filename, Charset encoding)
  5. readFileToString(String path, Charset charset)
  6. readInputStream(InputStream stream, Charset cs)
  7. readInputStreamToString(InputStream instream, Charset charset)
  8. readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)
  9. readLines(InputStream in, Charset cs)