复制代码代码如下:
публичная статическая строка getCharset (файл файла) {
String charset = "gbk";
byte [] first3bytes = new Byte [3];
пытаться {
Boolean проверено = false;
BufferedInputStream bis = new BufferedInputStream (
new FileInputStream (файл));
bis.mark (0);
int Read = bis.read (First3bytes, 0, 3);
if (read == -1)
вернуть Чарсет;
if (first3bytes [0] == (byte) 0xff && first3bytes [1] == (byte) 0xfe) {
charset = "utf-16le";
проверено = true;
} else if (first3bytes [0] == (byte) 0xfe && first3bytes [1]
== (byte) 0xff) {
charset = "utf-16be";
проверено = true;
} else if (first3bytes [0] == (byte) 0xef && first3bytes [1]
== (байт) 0xbb
&& first3bytes [2] == (byte) 0xbf) {
charset = "utf-8";
проверено = true;
}
bis.reset ();
if (! Проверено) {
int loc = 0;
while ((read = bis.read ())! = -1) {
loc ++;
if (Read> = 0xf0)
перерыв;
// 单独出现 bf 以下的 , 也算是 gbk
if (0x80 <= Read && Read <= 0xbf)
перерыв;
if (0xc0 <= Read && Read <= 0xdf) {
read = bis.read ();
if (0x80 <= Read && Read <= 0xbf) // 双字节 (0xc0 - 0xdf)
// (0x80 -
// 0xbf), 也可能在 gb 编码内
продолжать;
еще
перерыв;
// 也有可能出错 , 但是几率较小
} else if (0xe0 <= Read && Read <= 0xef) {
read = bis.read ();
if (0x80 <= Read && Read <= 0xbf) {
read = bis.read ();
if (0x80 <= Read && Read <= 0xbf) {
charset = "utf-8";
перерыв;
} еще
перерыв;
} еще
перерыв;
}
}
System.out.println (loc + "" + integer.tohexstring (read));
}
bis.close ();
} catch (Exception e) {
e.printstacktrace ();
}
вернуть Чарсет;
}