判断二进制流编码

来源:互联网 发布:php 记录蜘蛛程序 编辑:程序博客网 时间:2024/05/18 01:50

添加jar包 chardet-1.0.jar  cpdetector_1.0.10.jar   jargs-1.0.jar


/**                                                                            * 获得文件流的编码格式           * detector是探测器,它把探测任务交给具体的探测实现类的实例完成。      * cpDetector内置了一些常用的探测实现类,这些探测实现类的实例可以通过add方法 加进来,如ParsingDetector、      * JChardetFacade、ASCIIDetector、UnicodeDetector。      * detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则返回探测到的      * 字符集编码。使用需要用到三个第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar      * cpDetector是基于统计学原理的,不保证完全正确。      * JChardetFacade封装了由Mozilla组织提供的JChardet,它可以完成大多数文件的编码      * 测定。所以,一般有了这个探测器就可满足大多数项目的要求,如果你还不放心,可以      * 再多加几个探测器,比如下面的ASCIIDetector、UnicodeDetector等。  * @throws IOException  * @throws IllegalArgumentException */                                                                              public static String getInputStreamEncode(InputStream is) throws IOException { String charsetName = null;try{LOG.debug("默认编码:"+Charset.defaultCharset());   CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();             detector.add(new ParsingDetector(false));                                         detector.add(JChardetFacade.getInstance());                                       detector.add(ASCIIDetector.getInstance());                                        detector.add(UnicodeDetector.getInstance());                                      Charset charset = null;   int p = (is.read() << 8) + is.read();   try {                                                                              charset = detector.detectCodepage(is,p);                                     } catch (Exception ex) {                                                           ex.printStackTrace();                                                           }                                                                                 if (charset != null) {                                                            charsetName=  charset.name();                                                          } else {                                                                          charsetName =  "utf-8";                                                                 }  } catch(Exception e){ e.printStackTrace(); } return charsetName;} 


0 0