java判断文件编码集


 由于程序需要导入一些文本文件,所以碰到文件编码问题。原来想输入的文本文件都用utf-8编码格式问题就解决了,但是后来发现,需要导入的文件,是由第三方来提供的,格式我们控制不了,所以在导入前需要检测文件的编码,然后根据编码来读入,以避免乱码问题。

        经过一番查找,发现用现成的第三方jar包比较简单、可靠。需要的jar包:cpdetector_1.0.8.jar,另外需要依赖antlr-2.7.2.jar和chardet.jar包,网上下载地址很多,就不上传了。

       开源项目:cpdetector,它所在的网址是:http://www.oschina.net/p/cpdetector。


    FileEncodeDetector

    package cn.edu.cqu.tiger;

    import info.monitorenter.cpdetector.io.ASCIIDetector;

    import info.monitorenter.cpdetector.io.CodepageDetectorProxy;

    import info.monitorenter.cpdetector.io.JChardetFacade;

    import info.monitorenter.cpdetector.io.ParsingDetector;

    import info.monitorenter.cpdetector.io.UnicodeDetector;

    import java.io.BufferedReader;

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.InputStreamReader;

    public class FileEncodeDetector {

        public static String getFileEncode(String path) {

           /*------------------------------------------------------------------------

             detector是探测器,它把探测任务交给详细的探测实现类的实例完成。

             cpDetector内置了一些常用的探测实现类,这些探测实现类的实例可以通过add方法

             加进来,如ParsingDetector、 JChardetFacade、ASCIIDetector、UnicodeDetector。

             detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则返回探测到的

             字符集编码。

              使用需要用到三个第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar

              cpDetector是基于统计学原理的,不保证完全准确。

           --------------------------------------------------------------------------*/

           CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();

           /*-------------------------------------------------------------------------

             ParsingDetector可用于检查HTML、XML等文件或字符流的编码,构造方法中的参数用于

             指示是否显示探测过程的具体信息,为false不显示。

           ---------------------------------------------------------------------------*/

           detector.add(new ParsingDetector(false));

/*--------------------------------------------------------------------------

             JChardetFacade封装了由Mozilla组织提供的JChardet,它可以完成大多数文件的编码

             测定。所以,一般有了这个探测器就可知足大多数项目的要求,假如你还不放心,可以

             再多加几个探测器,好比下面的ASCIIDetector、UnicodeDetector等。

            ---------------------------------------------------------------------------*/

           detector.add(JChardetFacade.getInstance());//用到antlr.jar、chardet.jar

           // ASCIIDetector用于ASCII编码测定

           detector.add(ASCIIDetector.getInstance());

           // UnicodeDetector用于Unicode家族编码的测定

           detector.add(UnicodeDetector.getInstance());

           java.nio.charset.Charset charset = null;

           File f = new File(path);

           try {

               charset = detector.detectCodepage(f.toURI().toURL());

           } catch (Exception ex) {

               ex.printStackTrace();

           }

           if (charset != null)

               return charset.name();

           else

               return null;

        }

        public static void main(String[] args) throws IOException,

               FileNotFoundException {

           String path = "J:\\Unicode\\ub.txt";

           //Windows下Unicode探测后得到Windows-1252

           String encode = getFileEncode(path);

           if("Windows-1252".equalsIgnoreCase(encode))

               encode = "Unicode";

           File file = new File(path);

           InputStream ios = new java.io.FileInputStream(file);

           byte[] b = new byte[3];

           ios.read(b);

           ios.close();

           if (b[0] == -17 && b[1] == -69 && b[2] == -65)//文件头

               System.out.println(file.getName() + ":编码为UTF-8");

           else

               System.out.println(file.getName() + ":可能是GBK,也可能是其他编码。");

           BufferedReader bufferedReader = new BufferedReader(

                  new InputStreamReader(new FileInputStream(file), encode));

           System.out.println(encode);

           System.out.println(bufferedReader.readLine().substring(1));//去掉第一行中的文件头

        }

    }

    上面代码中的detector不仅可以用于探测文件的编码,也可以探测任意输入的文本流的编码,方法是调用其重载形式:

    charset=detector.detectCodepage(InputStream in, int length);

    上面的字节数由程序员指定,字节数越多,判断越正确,当然时间也花得越长。要留意,字节数的指定不能超过文本流的最大长度。

    判断文件编码的详细应用举例:

    属性文件(.properties)是Java程序中的常用文本存储方式,象STRUTS框架就是利用属性文件存储程序中的字符串资源。它的内容如下所示:

    #注释语句

    属性名=属性值

    读入属性文件的一般方法是:

      FileInputStream ios=new FileInputStream(“属性文件名”);

      Properties prop=new Properties();

      prop.load(ios);

      ios.close();

    利用java.io.Properties的load方法读入属性文件固然利便,但假如属性文件中有中文,在读入之后就会发现泛起乱码现象。发生这个原因是load方法使用字节流读入文本,在读入后需要将字节流编码成为字符串,而它使用的编码是“iso-8859-1”,这个字符集是ASCII码字符集,不支持中文编码,所以这时需要使用显式的转码:

       String value=prop.getProperty(“属性名”);

       String encValue=new String(value.getBytes(“iso-8859-1″),”属性文件的实际编码”);

    在上面的代码中,属性文件的实际编码就可以利用上面的方法获得。当然,象这种属性文件是项目内部的,我们可以控制属性文件的编码格局,好比商定采用Windows内定的GBK,就直接利用”gbk”来转码,假如商定采用UTF-8,也可以是使用”UTF-8″直接转码。假如想灵活一些,做到自动探测编码,就可利用上面先容的方法测定属性文件的编码,从而利便开发职员的工作。

    可以用下面代码获得Java支持编码集合:

    Charset.availableCharsets().keySet();

    可以用下面的代码获得系统默认编码:

    Charset.defaultCharset();


cpdetector  jar 下载


/**                                                                              
* 获得远程URL文件的编码格式                                                     
*/                                                                              
public static String getReomoteURLFileEncode(URL url) {                          
   CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();          
   detector.add(new ParsingDetector(false));                                      
   detector.add(JChardetFacade.getInstance());                                    
   detector.add(ASCIIDetector.getInstance());                                     
   detector.add(UnicodeDetector.getInstance());                                   
   java.nio.charset.Charset charset = null;                                       
   try {                                                                          
    System.out.println(url);                                                     
    charset = detector.detectCodepage(url);                                      
   } catch (Exception ex) {                                                       
    ex.printStackTrace();                                                        
   }                                                                              
   if (charset != null) {                                                         
    return charset.name();                                                       
   } else {                                                                       
    return "utf-8";                                                              
   }                                                                              
}                                                                                
                                                                                  
                                                                                  
/**                                                                              
* 获得文件流的编码格式                                                          
*/                                                                              
public static String getInputStreamEncode(InputStream is) {                      
   CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();          
   detector.add(new ParsingDetector(false));                                      
   detector.add(JChardetFacade.getInstance());                                    
   detector.add(ASCIIDetector.getInstance());                                     
   detector.add(UnicodeDetector.getInstance());                                   
   java.nio.charset.Charset charset = null;                                       
   try {                                                                          
    charset = detector.detectCodepage(is, 0);                                    
   } catch (Exception ex) {                                                       
    ex.printStackTrace();                                                        
   }                                                                              
   if (charset != null) {                                                         
    return charset.name();                                                       
   } else {                                                                       
    return "utf-8";                                                              
   }                                                                              
}                                                                                
                                                                                  
/**                                                                              
* 获得本地文件的编码格式                                                        
*/                                                                              
public static String getLocalteFileEncode(String filePath) {                     
   CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();          
   detector.add(new ParsingDetector(false));                                      
   detector.add(JChardetFacade.getInstance());                                    
   detector.add(ASCIIDetector.getInstance());                                     
   detector.add(UnicodeDetector.getInstance());                                   
   java.nio.charset.Charset charset = null;                                       
   File file = new File(filePath);                                                
   try {                                                                          
    charset = detector.detectCodepage(file.toURI().toURL());                     
   } catch (Exception ex) {                                                       
    ex.printStackTrace();                                                        
   }                                                                              
   if (charset != null) {                                                         
    return charset.name();                                                       
   } else {                                                                       
    return "utf-8";                                                              
   }                                                                              
}                                                                                
/**                                                                              
* 获得字符串的编码格式                                                          
*/                                                                              
public static String getStringEncode(String str) {                               
   CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();          
   detector.add(new ParsingDetector(false));                                      
   detector.add(JChardetFacade.getInstance());                                    
   detector.add(ASCIIDetector.getInstance());                                     
   detector.add(UnicodeDetector.getInstance());                                   
   java.nio.charset.Charset charset = null;                                       
   InputStream myIn=new ByteArrayInputStream(str.getBytes());                     
   try {                                                                          
    charset = detector.detectCodepage(myIn,3);                                   
   } catch (Exception ex) {                                                       
    ex.printStackTrace();                                                        
   }                                                                              
   if (charset != null) {                                                         
    return charset.name();                                                       
   } else {                                                                       
    return "utf-8";                                                              
   }                                                                              
}                                                                                

你可能感兴趣的:(java判断文件编码集)