Java File to String fileToString(File file, String charsetName)

Here you can find the source of fileToString(File file, String charsetName)

Description

file To String

License

Open Source License

Declaration

public static String fileToString(File file, String charsetName) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

public class Main {
    public static String fileToString(File file, String charsetName) throws IOException {
        FileInputStream in = new FileInputStream(file);
        try {/*from w  w  w  . j av  a  2s.  c  om*/
            return allToString(new InputStreamReader(in, charsetName));
        } finally {
            in.close();
        }
    }

    public static String allToString(InputStream is, String charsetName) throws IOException {
        if (is instanceof ByteArrayInputStream) {
            byte[] bytes = new byte[is.available()];
            //noinspection ResultOfMethodCallIgnored
            is.read(bytes);
            return new String(bytes, charsetName);
        }

        return allToString(new InputStreamReader(is, charsetName));
    }

    public static String allToString(Reader in) throws IOException {
        StringBuilder buf = new StringBuilder();
        int size = 16384;
        char[] str = new char[size];
        int n;
        while ((n = in.read(str, 0, size)) > 0) {
            buf.append(str, 0, n);
        }
        return buf.toString();
    }
}

Related

  1. fileToString(File file)
  2. fileToString(File file)
  3. fileToString(File file)
  4. fileToString(File file)
  5. fileToString(File file, int max)
  6. fileToString(File file, String charsetName)
  7. fileToString(File files[])
  8. fileToString(final File file)
  9. fileToString(final File file, final String charsetName)