复制代码代码如下:
السلسلة الثابتة العامة getCharset (ملف الملف) {
String charset = "GBK" ؛
byte [] first3bytes = new byte [3] ؛
يحاول {
فحص منطقي = خطأ ؛
BufferedInputStream BIS = جديد BufferedInputStream (
FileInputStream جديد (ملف)) ؛
bis.mark (0) ؛
int read = bis.read (first3bytes ، 0 ، 3) ؛
إذا (اقرأ == -1)
إرجاع charset
if (first3bytes [0] == (byte) 0xff && first3bytes [1] == (byte) 0xfe) {
charset = "utf-16le" ؛
فحص = صحيح ؛
} آخر إذا (first3bytes [0] == (byte) 0xfe && first3bytes [1]
== (بايت) 0xff) {
charset = "utf-16be" ؛
فحص = صحيح ؛
} آخر إذا (first3bytes [0] == (byte) 0xef && first3bytes [1]
== (بايت) 0xBB
&& first3bytes [2] == (byte) 0xbf) {
charset = "utf-8" ؛
فحص = صحيح ؛
}
bis.reset () ؛
إذا (! فحص) {
int loc = 0 ؛
بينما ((read = bis.read ())! = -1) {
loc ++ ؛
إذا (اقرأ> = 0xF0)
استراحة؛
// 单独出现 bf 以下的 , 也算是 gbk
if (0x80 <= read && read <= 0xBF)
استراحة؛
if (0xc0 <= read && read <= 0xdf) {
قراءة = bis.read () ؛
if (0x80 <= read && read <= 0xbf) // 双字节 (0xc0 - 0xDF)
// (0x80 -
// 0xbf) ، 也可能在 gb 编码内
يكمل؛
آخر
استراحة؛
// 也有可能出错 , 但是几率较小
} آخر إذا (0xe0 <= read && read <= 0xef) {
قراءة = bis.read () ؛
if (0x80 <= read && read <= 0xbf) {
قراءة = bis.read () ؛
if (0x80 <= read && read <= 0xbf) {
charset = "utf-8" ؛
استراحة؛
} آخر
استراحة؛
} آخر
استراحة؛
}
}
System.out.println (loc + "" + integer.toHexString (read)) ؛
}
bis.close () ؛
} catch (استثناء e) {
E.PrintStackTrace () ؛
}
إرجاع charset
}