日期:2014-05-20 浏览次数:20879 次
public static void main(String[] args) {
try {
String charset = getCharset(new File("c:\\2.txt"));
System.out.println(charset);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String toHex(byte[] byteArray) {
int i;
StringBuffer buf = new StringBuffer("");
int len = byteArray.length;
for (int offset = 0; offset < len; offset++) {
i = byteArray[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString().toUpperCase();
}
private static String getCharset(File fileName) throws IOException {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
byte[] b = new byte[10];
bin.read(b, 0, b.length);
String first = toHex(b);
//这里可以看到各种编码的前几个字符是什么,gbk编码前面没有多余的
String code = null;
if (first.startsWith("EFBBBF")) {
code = "UTF-8";
} else if (first.startsWith("FEFF00")) {