判断文件的编码

首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下:



ANSI: 无格式定义;

Unicode: 前两个字节为FFFE;

Unicode big endian: 前两字节为FEFF;

UTF-8: 前两字节为EFBB;



知道了各种编码格式的区别,写代码就容易了.



  1. publicstaticString get_charset( File file ) {
  2. String charset ="GBK";
  3. byte[] first3Bytes =newbyte[3];
  4. try{
  5. boolean;
  6. BufferedInputStream bis =newBufferedInputStream(newFileInputStream( file ) );
  7. bis.mark(0);
  8. intread = bis.read( first3Bytes,0,3);
  9. if( read == -1)returncharset;
  10. if( first3Bytes[0] == (byte)0xFF&& first3Bytes[1] == (byte)0xFE) {
  11. charset ="UTF-16LE";
  12. checked =true;
  13. }
  14. elseif( first3Bytes[0] == (byte)0xFE&& first3Bytes[1] == (byte)0xFF) {
  15. charset ="UTF-16BE";
  16. checked =true;
  17. }
  18. elseif( first3Bytes[0] == (byte)0xEF&& first3Bytes[1] == (byte)0xBB&& first3Bytes[2] == (byte)0xBF) {
  19. charset ="UTF-8";
  20. checked =true;
  21. }
  22. bis.reset();
  23. if( !checked ) {
  24. // int len = 0;
  25. intloc =0;
  26. while( (read = bis.read()) != -1) {
  27. loc++;
  28. if( read >=0xF0)break;
  29. if(0x80<= read && read <=0xBF)// 单独出现BF以下的,也算是GBK
  30. break;
  31. if(0xC0<= read && read <=0xDF) {
  32. read = bis.read();
  33. if(0x80<= read && read <=0xBF)// 双字节 (0xC0 - 0xDF) (0x80
  34. // - 0xBF),也可能在GB编码内
  35. continue;
  36. elsebreak;
  37. }
  38. elseif(0xE0<= read && read <=0xEF) {// 也有可能出错,但是几率较小
  39. read = bis.read();
  40. if(0x80<= read && read <=0xBF) {
  41. read = bis.read();
  42. if(0x80<= read && read <=0xBF) {
  43. charset ="UTF-8";
  44. break;
  45. }
  46. elsebreak;
  47. }
  48. elsebreak;
  49. }
  50. }
  51. //System.out.println( loc + " " + Integer.toHexString( read ) );
  52. }
  53. bis.close();
  54. }catch( Exception e ) {
  55. e.printStackTrace();
  56. }
  57. returncharset;
  58. }From: http://ajava.org/code/I18N/14816.html

原文链接: https://www.cnblogs.com/xyzlmn/archive/2010/01/02/3168318.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/6258

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月6日 下午2:24
下一篇 2023年2月6日 下午2:27

相关推荐