Java Text File Read by Charset readFileToString(String filename, Charset encoding)

Here you can find the source of readFileToString(String filename, Charset encoding)

Description

read File To String

License

Open Source License

Declaration

public static String readFileToString(String filename, Charset encoding) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;

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

import java.nio.charset.Charset;

public class Main {
    private static final int BUFFER_SIZE = 4 * 1024;

    public static String readFileToString(String filename, Charset encoding) throws IOException {
        return readStreamToString(new FileInputStream(filename), encoding);
    }/*w ww  . ja  va 2  s .  co m*/

    public static String readFileToString(File file, Charset encoding) throws IOException {
        return readStreamToString(new FileInputStream(file), encoding);
    }

    public static String readStreamToString(InputStream stream, Charset encoding) throws IOException {
        StringBuilder builder = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(stream, encoding);
        char[] buffer = new char[BUFFER_SIZE];
        int length;
        while ((length = reader.read(buffer)) != -1) {
            builder.append(buffer, 0, length);
        }
        reader.close();
        return builder.toString();
    }
}

Related

  1. readFile(String path, Charset encoding)
  2. readFileAsString(String path, String charsetName)
  3. readFileContents(File file, Charset charset)
  4. readFileToLines(String inFile, String inCharset)
  5. readFileToList(String filePath, String charsetName)
  6. readFileToString(String path, Charset charset)
  7. readFromInputStream(InputStream stream, Charset charset)
  8. readInputStream(InputStream stream, Charset cs)
  9. readInputStreamToString(InputStream instream, Charset charset)