判断文件字符集类型

论坛 期权论坛 脚本     
已经匿名di用户   2022-4-26 15:50   2207   0

在开发中,我们经常会遇到文件乱码问题,如果我们有一个工具可以判断文件类型,这时对于我们的编码转换就方便多了。

/**
* 根据传入的文件,判断文件的字符集类型
* @param fileName 传入文件的路径
* @return
* @throws IOException
*/

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")) {
code = "UTF-16BE";
} else if (first.startsWith("FFFE")) {
code = "Unicode";
} else if (first.startsWith("FFFE")) {
code = "Unicode";
} else {
code = "GBK";
}
return code;

}


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();

}

public static void main(String[] args) {
try {
String charset = getCharset(new File("e://test1/AM00006D.ply"));
System.out.println(charset);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP