首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

java 怎么判断txt的编码字符集

2013-04-02 
java 如何判断txt的编码字符集最近在做一个文本阅读器,显示时需要获得本地导入的txt的编码字符集,网上搜了

java 如何判断txt的编码字符集
最近在做一个文本阅读器,显示时需要获得本地导入的txt的编码字符集,网上搜了,都不行,还在搜,请高手给个成熟的方法,谢谢了。在线狂等中.
我的代码(不可用):
private static void judgeTextCode(String strFilePath) {
FileInputStream fis = null;
try {
fis = new FileInputStream(strFilePath);
int a = fis.read();
int b = fis.read();
if(a==0xFF&&b==0xFE) {
System.out.println("----------Unicode------");

else if(a==0xFE&&b==0xFF) {
System.out.println("----------UTF-16BE------");
}
else if(a==0xEF&&b==0xBB) {
System.out.println("----------UTF-8------");
} else {
System.out.println("----------GBK------");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(fis != null) {
fis.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}

} java
[解决办法]



public static void main(String[] args) {
try {
String charset = getCharset(new File("c:\\2.txt"));
System.out.println(charset);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 public static String toHex(byte[] byteArray) {
        int i;
        StringBuffer buf = new StringBuffer("");
        int len = byteArray.length;
        for (int offset = 0; offset < len; offset++) {
            i = byteArray[offset];
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        return buf.toString().toUpperCase();
    }
  private static String getCharset(File fileName) throws IOException {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
        byte[] b = new byte[10];
        bin.read(b, 0, b.length);
        String first = toHex(b);
 //这里可以看到各种编码的前几个字符是什么,gbk编码前面没有多余的
        String code = null;
        if (first.startsWith("EFBBBF")) {
            code = "UTF-8";
        } else if (first.startsWith("FEFF00")) {


            code = "UTF-16BE";
        } else if (first.startsWith("FFFE")) {
            code = "Unicode";
        } else if (first.startsWith("FFFE")) {
            code = "Unicode";
        } else {
            code = "GBK";
        }
        return code;
    }


[解决办法]
65465461313113131313
[解决办法]
txt就四种编码。
[解决办法]
else {
                code = "GBK";
            }

GBK改为ANSI

热点排行