java怎么获取文件编码格式?

String path = "E:/temp/logcat/01_testcase/bbb.txt";
InputStream inputStream = new FileInputStream(path);
byte[] head = new byte[300];
inputStream.read(head);
String code = "";
System.out.print(" " + head[0]);
System.out.print(" " + head[1]);
System.out.println(" " + head[3]);

if (head[0] == -1 && head[1] == -2) {
code = "UTF-16";
} else if (head[0] == -2 && head[1] == -1) {
code = "Unicode";
} else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
code = "UTF-8";
}

bbb.txt中的内容是abcd
运行结果:head[0]=97 head[1]=98 head[2]=100
head的运行结果并不是预期的 -17 -69 -65. 这是什么原因啊?

没错,就这样做,文件格式和文件内容,不是这样的。

普通文件,开始就是文件内容了。

有编码的,开头先是编码的定义,正如判断语句所写的那样追问

1、什么样的文件不是普通文件?右键新建文本文档是普通文件?
2、有2个文件:aaa.txt bbb.txt
在本机双击打开时,aaa.txt默认编码是UTF-8 bbb.txt默认编码是GB2312
用上面的程序运行时 都不能获取正确的编码。

追答

最标准的途径是检测文本最开头的几个字节,开头字节 Charset/encoding,如下表:

EF BB BF  UTF-8
FE FF    UTF-16/UCS-2, little endian
FF FE    UTF-16/UCS-2, big endian
FF FE 00 00 UTF-32/UCS-4, little endian.
00 00 FE FF UTF-32/UCS-4, big-endian.

int[] head = new int[4];
InputStream inputStream = new FileInputStream(path);
for(int i=0; i<4; i++){

head[0]=inputStream.read();
}
inputStream.close();

String code = "ANSI";
if (head[0]==0xef && head[1]==0xbb && head[2]==0xbf) {
code = "UTF-8";

} else if(head[0]==0xfe && head[1]==0xff) {
code = "utf-16/ucs2, little endian";

} else if(head[0]==0xff && head[1]==0xfe) {
code = "utf-16/ucs2, big endian";

} else if(head[0]==0xff && head[1]==0xfe && head[2]==0x0 && head[3]==0x0) {
code = "UTF-32/ucs4, little endian";

} else if (head[0]==0x0 && head[1]==0x0 && head[2]==0xfe && head[3]==0xff) {
code = "UTF-32/ucs4, big endian";
}

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网