`

Java正确判别出文件的字符集(尤其是带BOM和不带BOM的UTF-8字符)

    博客分类:
  • JAVA
 
阅读更多

Java正确判别出文件的字符集(尤其是带BOM和不带BOM的UTF-8字符)

前几天在项目中需要读取用户上传过来的txt文件,但不确定txt文件的字符集

UTF-16、UTF-8(带BOM)、Unicode可以根据前三个字节区别 

 

[java] view plaincopy
 
  1. public String getTxtEncode(FileInputStream in) throws IOException{  
  2.         byte[] head = new byte[3];    
  3.         in.read(head);      
  4.         String code = "GBK";    
  5.         if (head[0] == -1 && head[1] == -2 )    
  6.             code = "UTF-16";    
  7.         if (head[0] == -2 && head[1] == -1 )    
  8.             code = "Unicode";  
  9.         //带BOM  
  10.         if(head[0]==-17 && head[1]==-69 && head[2] ==-65)    
  11.             code = "UTF-8";    
  12.         if("Unicode".equals(code)){  
  13.          code = "UTF-16";  
  14.         }  
  15.         return code;  
  16.  }  

 

但不带BOM的UTF-8和GBK前三个字节不确定,用以上方法无法区别

 

通过在google上搜索发现不带BOM的识别是Java遗留的一个bug,呵呵,终于找到根源了,Java提供了此bug的解决方案

[java] view plaincopy
 
  1. package com.justsy.sts.utf8;  
  2.   
  3. import java.io.*;    
  4.   
  5. /**  
  6.  * This inputstream will recognize unicode BOM marks and will skip bytes if  
  7.  * getEncoding() method is called before any of the read(...) methods.  
  8.  *   
  9.  * Usage pattern: String enc = "ISO-8859-1"; // or NULL to use systemdefault  
  10.  * FileInputStream fis = new FileInputStream(file); UnicodeInputStream uin = new  
  11.  * UnicodeInputStream(fis, enc); enc = uin.getEncoding(); // check and skip  
  12.  * possible BOM bytes InputStreamReader in; if (enc == null) in = new  
  13.  * InputStreamReader(uin); else in = new InputStreamReader(uin, enc);  
  14.  */    
  15. public class UnicodeInputStream extends InputStream {    
  16.     PushbackInputStream internalIn;    
  17.     boolean isInited = false;    
  18.     String defaultEnc;    
  19.     String encoding;    
  20.     
  21.     private static final int BOM_SIZE = 4;    
  22.     
  23.     public UnicodeInputStream(InputStream in, String defaultEnc) {    
  24.         internalIn = new PushbackInputStream(in, BOM_SIZE);    
  25.         this.defaultEnc = defaultEnc;    
  26.     }    
  27.     
  28.     public String getDefaultEncoding() {    
  29.         return defaultEnc;    
  30.     }    
  31.     
  32.     public String getEncoding() {    
  33.         if (!isInited) {    
  34.             try {    
  35.                 init();    
  36.             } catch (IOException ex) {    
  37.                 IllegalStateException ise = new IllegalStateException(    
  38.                         "Init method failed.");    
  39.                 ise.initCause(ise);    
  40.                 throw ise;    
  41.             }    
  42.         }    
  43.         return encoding;    
  44.     }    
  45.     
  46.     /**  
  47.      * Read-ahead four bytes and check for BOM marks. Extra bytes are unread  
  48.      * back to the stream, only BOM bytes are skipped.  
  49.      */    
  50.     protected void init() throws IOException {    
  51.         if (isInited)    
  52.             return;    
  53.     
  54.         byte bom[] = new byte[BOM_SIZE];    
  55.         int n, unread;    
  56.         n = internalIn.read(bom, 0, bom.length);    
  57.     
  58.         if ((bom[0] == (byte0x00) && (bom[1] == (byte0x00)    
  59.                 && (bom[2] == (byte0xFE) && (bom[3] == (byte0xFF)) {    
  60.             encoding = "UTF-32BE";    
  61.             unread = n - 4;    
  62.         } else if ((bom[0] == (byte0xFF) && (bom[1] == (byte0xFE)    
  63.                 && (bom[2] == (byte0x00) && (bom[3] == (byte0x00)) {    
  64.             encoding = "UTF-32LE";    
  65.             unread = n - 4;    
  66.         } else if ((bom[0] == (byte0xEF) && (bom[1] == (byte0xBB)    
  67.                 && (bom[2] == (byte0xBF)) {    
  68.             encoding = "UTF-8";    
  69.             unread = n - 3;    
  70.         } else if ((bom[0] == (byte0xFE) && (bom[1] == (byte0xFF)) {    
  71.             encoding = "UTF-16BE";    
  72.             unread = n - 2;    
  73.         } else if ((bom[0] == (byte0xFF) && (bom[1] == (byte0xFE)) {    
  74.             encoding = "UTF-16LE";    
  75.             unread = n - 2;    
  76.         } else {    
  77.             // Unicode BOM mark not found, unread all bytes    
  78.             encoding = defaultEnc;    
  79.             unread = n;    
  80.         }    
  81.         // System.out.println("read=" + n + ", unread=" + unread);    
  82.     
  83.         if (unread > 0)    
  84.             internalIn.unread(bom, (n - unread), unread);    
  85.     
  86.         isInited = true;    
  87.     }    
  88.     
  89.     public void close() throws IOException {    
  90.         // init();    
  91.         isInited = true;    
  92.         internalIn.close();    
  93.     }    
  94.     
  95.     public int read() throws IOException {    
  96.         // init();    
  97.         isInited = true;    
  98.         return internalIn.read();    
  99.     }    
  100. }  

通过使用上述InputStream类的实现可以正确的读取出不带BOM和带BOM的字符集

[java] view plaincopy
 
  1. package com.justsy.sts.utf8;  
  2.   
  3. import java.io.BufferedReader;    
  4. import java.io.File;    
  5. import java.io.FileInputStream;    
  6. import java.io.IOException;    
  7. import java.io.InputStreamReader;  
  8. import java.nio.charset.Charset;  
  9.     
  10. public class UTF8Test {    
  11.     public static void main(String[] args) throws IOException {    
  12.         File f  = new File("D:"+File.separator+"Order.txt");    
  13.         FileInputStream in = new FileInputStream(f);    
  14.         String dc  = Charset.defaultCharset().name();  
  15.         UnicodeInputStream uin = new UnicodeInputStream(in,dc);  
  16.         BufferedReader br = new BufferedReader(new InputStreamReader(uin));    
  17.         String line = br.readLine();    
  18.         while(line != null)    
  19.         {    
  20.             System.out.println(line);    
  21.             line = br.readLine();    
  22.         }    
  23.     }    
  24. }  


结合Java提供的方案,我们就可以比较完整的判别出各种字符集了

[java] view plaincopy
 
  1. public String getTxtEncode(FileInputStream in) throws IOException{  
  2.    
  3.  String dc  = Charset.defaultCharset().name();  
  4.        UnicodeInputStream uin = new UnicodeInputStream(in,dc);  
  5.          
  6.        if("UTF-8".equals(uin.getEncoding())){  
  7.         uin.close();  
  8.         return "UTF-8";  
  9.        }  
  10.        uin.close();  
  11.          
  12.        byte[] head = new byte[3];    
  13.        in.read(head);      
  14.        String code = "GBK";    
  15.        if (head[0] == -1 && head[1] == -2 )    
  16.            code = "UTF-16";    
  17.        if (head[0] == -2 && head[1] == -1 )    
  18.            code = "Unicode";  
  19.        //带BOM  
  20.        if(head[0]==-17 && head[1]==-69 && head[2] ==-65)    
  21.            code = "UTF-8";    
  22.        if("Unicode".equals(code)){  
  23.         code = "UTF-16";  
  24.        }  
  25.        return code;  
  26. }  

本文的转载地址为:http://blog.csdn.net/tibib/article/details/7988735

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics