txt文件编码判断
2015-09-17 14:49
281 查看
txt文件,首先分有无bom(Byte Order Mark)。有的话,相对简单,没有的话,还要区分uft-8和ANSI的区别。代码如下:
private static boolean isutf8(byte[] str) { int i = 0; int size = str.length; while(i < size) { int step = 0; if((str[i] & 0x80) == 0x00) { step = 1; } else if((str[i] & 0xe0) == 0xc0) { if(i + 1 >= size) return false; if((str[i + 1] & 0xc0) != 0x80) return false; step = 2; } else if((str[i] & 0xf0) == 0xe0) { if(i + 2 >= size) return false; if((str[i + 1] & 0xc0) != 0x80) return false; if((str[i + 2] & 0xc0) != 0x80) return false; step = 3; } else { return false; } i += step; } if(i == size) return true; return false; } private static String getCode(byte[] bytes){ InputStream in = new ByteArrayInputStream(bytes); BufferedInputStream bin = new BufferedInputStream(in); String code = null;//判断字符编码 try { int p = (bin.read() << 8) + bin.read(); switch (p) { case 0xefbb: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: if(isutf8(bytes)) code = "UTF-8"; else{ code = "GBK"; } } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }finally{ try { bin.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return code; }
private static String getCode(byte[] bytes) { String hexCode = ""; if(bytes.length > 1){ for (int i = 0; i < 2; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } hexCode+=hex; } } String code = null;//判断字符编码 if(hexCode.toLowerCase().equals("efbb")) code = "UTF-8"; else if(hexCode.toLowerCase().equals("fffe")) code = "Unicode"; else if(hexCode.toLowerCase().equals("feff")) code = "UTF-16BE"; else{ if(isutf8(bytes)) code = "UTF-8"; else{ code = "GBK"; } } return code; }
相关文章推荐
- XML指南——XML编码
- C#中字符串编码处理
- ExtJS中文乱码之GBK格式编码解决方案及代码
- 程序员趣味读物 谈谈Unicode编码
- 文本文件编码方式区别
- C语言安全编码之数值中的sizeof操作符
- C#实现获取文本文件的编码的一个类(区分GB2312和UTF8)
- VC中BASE64编码和解码使用详解
- 计算机中的字符串编码、乱码、BOM等问题详解
- Base64编码解码原理及C#编程实例
- C#编码好习惯小结
- javascript编码的几个方法详细介绍
- UTF8编码开发中页面空白问题的解决方法
- php生成固定长度纯数字编码的方法
- 重新restore了mysql到另一台机器上后mysql 编码问题报错
- c# Base64编码和图片的互相转换代码
- java自动根据文件内容的编码来读取避免乱码
- PHP写入WRITE编码为UTF8的文件的实现代码
- 设置php页面编码的两种方法示例介绍
- js实现字符串的16进制编码不加密