Java Text File Read by Charset readAllText(File file, Charset charset)

Here you can find the source of readAllText(File file, Charset charset)

Description

read All Text

License

Open Source License

Declaration

public static String readAllText(File file, Charset charset) 

Method Source Code


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

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

public class Main {
    public static String readAllText(File file) {
        return readAllText(file, Charset.forName("UTF8"));
    }//from ww w.java 2 s.com

    public static String readAllText(File file, Charset charset) {
        try {
            return readAllText(new FileInputStream(file), charset);
        } catch (FileNotFoundException e) {
            return null;
        }
    }

    public static String readAllText(InputStream stream, Charset charset) {
        if (stream == null)
            return null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
        StringWriter writer = new StringWriter();
        copyAll(reader, writer);
        return writer.toString();
    }

    public static void copyAll(Reader reader, Writer writer) {
        try {
            char[] data = new char[4096]; // copy in chunks of 4K
            int count;
            while ((count = reader.read(data)) >= 0)
                writer.write(data, 0, count);

            reader.close();
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

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