java实现获取文件编码格式,经常用于读取文件内容。

1.使用java 语言IO流方式获取文档里面时,由于文档的不同编码方式要采用不同的字符集
eg:如下代码,需要我们用对应文件编码去读取。

   InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"utf-8");//file为文件对象
   reader = new BufferedReader(isr);
   String tempString = null;
   int line = 1;
   while ((tempString = reader.readLine()) != null) { // 一次读入一行,直到读入null为文件结束
        System.out.println("line " + line + ": " + tempString);
              //localBody=localBody+tempString+"\n";
       }

吐槽:刚开始也是网上找的别人的代码,见了最多是这个代码,然并没有效果!!!
在这里插入图片描述

2.常用的文件编码为UTF-8、GBK、ASCII等。获取文件编码格式的java代码实现如下:(目前个人只测试并使用了UTF-8、GBK、ASCII三种可行,其他格式能否识别不确定。用到的jar包detector放在下面地址!

try {
       bianMa=getFileCharsetName(file);//调用识别编码格式的逻辑
       System.out.println("编码格式为:"+bianMa);
     } catch (Exception e) {
        e.printStackTrace();
 }
     /** 获得文件编码
	 * @param file
	 * @return
      * @throws Exception
	 */

   public static String getFileCharsetName(File file) throws Exception {
        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
        detector.add(new ParsingDetector(false));
        detector.add(JChardetFacade.getInstance());
        detector.add(ASCIIDetector.getInstance());
        detector.add(UnicodeDetector.getInstance());
        Charset charset = null;
        try {
            charset = detector.detectCodepage(file.toURI().toURL());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        String charsetName = "GBK";
        if (charset != null) {
            if (charset.name().equals("US-ASCII")) {
                charsetName = "ISO_8859_1";
            } else if (charset.name().startsWith("UTF")) {
                charsetName = charset.name();// 例如:UTF-8,UTF-16BE.
            }else if(charset.name().equals("GB2312")){
                charsetName="GBK";
            }
        }
        return charsetName;//返回最终的编码格式
    }	  

引入依赖:

<!--        获取文件编码-->
        <dependency>
            <groupId>cpdetector</groupId>
            <artifactId>cpdetector</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>cpdetector</groupId>
            <artifactId>antlr</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>cpdetector</groupId>
            <artifactId>chardet</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>cpdetector</groupId>
            <artifactId>jargs</artifactId>
            <version>1.0</version>
        </dependency>

在这里插入图片描述
手动配置jar包的存放路径。。

detector包获取链接:https://pan.baidu.com/s/1fUahdV4TyWa9TQrc0ahouQ
提取码:wj5p

see you again!

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值