复制代码代码如下:
public static string getCharset (archivo de archivo) {
Cadena charset = "gbk";
byte [] first3bytes = new Byte [3];
intentar {
Boolean marcado = falso;
BufferedInputStream bis = new BufferedInputStream (
nuevo fileInputStream (archivo));
bis.mark (0);
int read = bis.read (First3bytes, 0, 3);
if (leer == -1)
devolver charset;
if (first3bytes [0] == (byte) 0xff && first3bytes [1] == (byte) 0xfe) {
charset = "utf-16le";
marcado = verdadero;
} else if (first3bytes [0] == (byte) 0xfe && first3bytes [1]
== (byte) 0xff) {
charset = "utf-16be";
marcado = verdadero;
} else if (first3bytes [0] == (byte) 0xef && first3bytes [1]
== (byte) 0xbb
&& first3bytes [2] == (byte) 0xbf) {
charset = "utf-8";
marcado = verdadero;
}
bis.reset ();
if (! checked) {
int loc = 0;
while ((read = bis.read ())! = -1) {
loc ++;
if (leer> = 0xf0)
romper;
// 单独出现 bf 以下的 , 也算是 gbk
if (0x80 <= read && read <= 0xbf)
romper;
if (0xc0 <= read && read <= 0xdf) {
read = bis.read ();
if (0x80 <= read && read <= 0xbf) // 双字节 (0xc0 - 0xdf)
// (0x80 -
// 0xbf), 也可能在 GB 编码内
continuar;
demás
romper;
// 也有可能出错 但是几率较小 但是几率较小
} 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";
romper;
} demás
romper;
} demás
romper;
}
}
System.out.println (loc + "" + integer.tohexString (read));
}
bis.close ();
} Catch (Exception e) {
E.PrintStackTrace ();
}
devolver charset;
}