Java Text File Read by Charset readFile(File file, String charsetName)

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

Description

read File

License

Apache License

Declaration

public static String readFile(File file, String charsetName) throws UnsupportedEncodingException 

Method Source Code


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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class Main {
    public static String readFile(File file, String charsetName) throws UnsupportedEncodingException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (FileInputStream is = new FileInputStream(file)) {
            int length = 0;
            byte[] bytes = new byte[1024 * 4];
            while ((length = is.read(bytes)) > 0) {
                baos.write(bytes, 0, length);
            }//  w  ww  . j  a va  2  s . c o m
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Charset charset = Charset.forName(charsetName);
        String value = new String(baos.toByteArray(), charset);
        if (value.getBytes(charset).length == baos.size()) {
            return value;
        }

        charset = Charset.forName("SJIS");
        value = new String(baos.toByteArray(), charset);
        if (value.getBytes(charset).length == baos.size()) {
            return value;
        }
        charset = Charset.forName("UTF8");
        value = new String(baos.toByteArray(), charset);
        return value;

    }
}

Related

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