复制代码代码如下 :
public static string getCharset (파일 파일) {
문자열 charset = "gbk";
바이트 [] first3bytes = 새로운 바이트 [3];
노력하다 {
부울 점검 = 거짓;
bufferedInputStream bis = 새로운 bufferedInputStream (
새 fileInputStream (file));
bis.mark (0);
int read = bis.Read (First3Bytes, 0, 3);
if (읽기 == -1)
반환 숯;
if (first3bytes [0] == (byte) 0xff && first3bytes [1] == (byte) 0xfe) {
charset = "utf-16le";
점검 = true;
} else if (first3bytes [0] == (byte) 0xfe && first3bytes [1]
== (바이트) 0xff) {
charset = "utf-16be";
점검 = true;
} else if (first3bytes [0] == (byte) 0xef && first3bytes [1]
== (바이트) 0xBB
&& first3Bytes [2] == (바이트) 0xBF) {
charset = "UTF-8";
점검 = true;
}
bis.reset ();
if (! checked) {
int loc = 0;
while ((read = bis.read ())! = -1) {
loc ++;
if (읽기> = 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 (예외 e) {
e.printstacktrace ();
}
반환 숯;
}