java实现获取文本文件的编码格式

jchardetmozilla自动字符集探测算法代码的java移植,其源代码可以从sourceforge下载

 

 

 

import org.mozilla.intl.chardet.HtmlCharsetDetector;

import org.mozilla.intl.chardet.nsDetector;

import org.mozilla.intl.chardet.nsICharsetDetectionObserver;

 

//方法 获取文件的编码格式

public String getCharSetEncoding(File file) throws Exception

    {

       boolean found=false;

       nsICharsetDetectionObserver ndo=new nsICharsetDetectionObserver() {

          

           public void Notify(String arg0) {

              HtmlCharsetDetector.found=true;

           }

       };

       nsDetector det=new nsDetector();

/**
*
初始化
nsDetector()
*lang
为一个整数,用以提示语言线索,可以提供的语言线索有以下几个:

*

   1. Japanese
   2. Chinese
   3. Simplified Chinese
   4. Traditional Chinese
   5. Korean
   6. Dont know (
默认
)
*/

//    nsDetector det=new nsDetector(lang);

       det.Init(ndo);

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

       byte[] buf=new byte[1024];

       boolean done=false;

       boolean isAscii=true;

       int length=0;

       while((length=bis.read(buf))!=-1)

       {

           if(isAscii)

           {

              isAscii=det.isAscii(buf, length);

           }

           if(!isAscii&&!done)

           {

              done=det.DoIt(buf, length, false);

           }

       }

       det.DataEnd();

       if(isAscii)

       {

           found=true;

           return "ASCII";

       }

       if(!found)

       {

           String pro[]=det.getProbableCharsets();//获取可能的编码格式

           if(pro.length>0)

           {

              return pro[0];//取第一个

           }

       }

       return null;

    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值