关于文件的字符集编码探测--java

来源:互联网 发布:国家的顶级域名 编辑:程序博客网 时间:2024/05/22 03:40

今天遇到一个要探测文件的字符集编码问题,查了一下资料,发现了一个 探测器: jchardet 需要  chardet.jar

 

例子如下:

**
   * 获取文件的编码
   *
   * @param file
   * @param det
   * @return
   * @throwsFileNotFoundException
   * @throws IOException
   *
  private StringgeestFileEncoding(File file, nsDetector det)
    throwsFileNotFoundException, IOException {
  
   det.Init(newnsICharsetDetectionObserver() {
    publicvoid Notify(String charset) {
     found= true;
     encoding= charset;
    }
   });

   BufferedInputStreamimp = new BufferedInputStream(new FileInputStream(
     file));

   byte[]buf = new byte[1024];
   intlen;
   boolean done= false;
   booleanisAscii = true;

   while((len = imp.read(buf, 0, buf.length)) != -1) {
    

    if(isAscii)
     isAscii= det.isAscii(buf, len);

    if(!isAscii && !done)
     done= det.DoIt(buf, len, false);
   }
   det.DataEnd();

   if(isAscii) {
    encoding= "ASCII";
    found= true;
   }

   if(!found) {
    Stringprob[] = det.getProbableCharsets();
    if(prob.length > 0) {
         encoding= prob[0];
    }else {
     returnnull;
    }
   }
   returnencoding;
  }

0 0
原创粉丝点击