Java Charset Guess getCharset(File file)

Here you can find the source of getCharset(File file)

Description

get Charset

License

Open Source License

Declaration

public static String getCharset(File file) 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;

import java.io.InputStream;

public class Main {
    public static String getCharset(File file) {
        String code = "GBK";
        FileInputStream fis = null;
        try {//www  . j a  va2s .  c  om
            byte[] head = new byte[3];
            fis = new FileInputStream(file);
            fis.read(head);
            code = getCharset(head);
        } catch (Exception e) {
            //
        } finally {
            closeInputStrem(fis);
        }
        return code;
    }

    public static String getCharset(byte[] head) {
        String code = "GBK";
        if (head[0] == (byte) 0xFF && head[1] == (byte) 0xFE) {
            code = "UTF-16LE";
        } else if (head[0] == (byte) 0xFE && head[1] == (byte) 0xFF) {
            code = "UTF-16BE";
        } else if (head[0] == (byte) 0xEF && head[1] == (byte) 0xBB && head[2] == (byte) 0xBF) {
            code = "UTF-8";
        }
        return code;
    }

    public static void closeInputStrem(InputStream in) {
        if (in == null)
            return;
        try {
            in.close();
        } catch (Exception e) {
            // TODO: Ignore it
        }
    }
}

Related

  1. getCharset(Object resource)
  2. getCharsetFileWriter(File file, String charset)
  3. getCharsetFromBytes(byte abyte0[])
  4. getCharSetStr(String str, String oldCharSet, String newCharSet)