Java Text File Read by Charset readFile(File file, Charset cs)

Here you can find the source of readFile(File file, Charset cs)

Description

read File

License

Apache License

Declaration

public static String readFile(File file, Charset cs) throws IOException 

Method Source Code


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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

public class Main {
    public static String readFile(File file, String csName) throws IOException {
        final Charset cs = Charset.forName(csName);
        return readFile(file, cs);
    }/* w  ww. j a  v a  2 s .c o m*/

    public static String readFile(File file, Charset cs) throws IOException {
        final FileInputStream stream = new FileInputStream(file);

        return readInputStream(stream, cs);
    }

    public static String readInputStream(InputStream stream, Charset cs) throws IOException {
        // No real need to close the BufferedReader/InputStreamReader
        // as they're only wrapping the stream

        try (final Reader reader = new BufferedReader(new InputStreamReader(stream, cs))) {
            final StringBuilder builder = new StringBuilder();
            final char[] buffer = new char[8192];
            int read;

            while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
                builder.append(buffer, 0, read);
            }

            return builder.toString();
        }
    }
}

Related

  1. readerBuffered(final File file, final Charset charset)
  2. readFile(Bundle bundle, String path, Charset cs)
  3. readFile(File f, Charset chst)
  4. readFile(File file, Charset charset)
  5. readFile(File file, Charset charset)
  6. readFile(File file, String charsetName)
  7. readFile(File theFile, Charset theCharset)
  8. readFile(final InputStream is, final Charset encoding)
  9. readFile(String path, Charset charset)