java采用三方工具包自动判断文件编码 两种方式

本文介绍了两种用于识别CSV文件编码格式的方法。第一种方法使用多种编码探测器组合,包括统计概率判断、字节顺序标记检测等,但可能不准确。第二种方法采用ICU4J库进行编码检测,能更准确地识别GB18030编码,适用于向下兼容的GB2312和GBK编码格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种我试过了不是很准,网上有人说是通过统计概率判断文件编码的再此处记录,

UTF8的CSV文件

用wps打开修改后保存,再用notepad打开显示为GB2312,该方法读取的编码格式为 UTF-16BE,按此格式读取文件出现乱码;

用excel2013打开修改后保存,再用notepad打开,看见格式仍然是GB2312,该方法判断文件编码格式为Big5,按此格式读取文件出现乱码;

jar包下载:
https://download.youkuaiyun.com/download/chen1280436393/11267094

    public static void getFileEncode(File file){
        String charsetName = null;
        try{
            CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
            detector.add(new ParsingDetector(false));
            detector.add(new ByteOrderMarkDetector());
            detector.add(JChardetFacade.getInstance());
            detector.add(ASCIIDetector.getInstance());
            detector.add(UnicodeDetector.getInstance());
            java.nio.charset.Charset charset = detector.detectCodepage(file.toURL());
            if (charset != null) {
                charsetName = charset.name();
            }else{
                charsetName = "GB2312";
            }
        }catch (Exception e){
           e.printStackTrace();
        }
        System.out.println("charsetName====="+charsetName);
    }

查到另外一种方式,读取成功,该方法判断文件编码格式为GB18030,

(GB2312(1980年)、GBK(1995年)到GB18030(2000年),这些编码方法是向下兼容的)

 public static void getFileCharsetByICU4J(File file) {
        String encoding = null;
        try {
            Path path = Paths.get(file.getPath());
            byte[] data = Files.readAllBytes(path);
            CharsetDetector detector = new CharsetDetector();
            detector.setText(data);
            CharsetMatch match = detector.detect();
            if (match == null) {
                 encoding = "默认";
            }
            encoding = match.getName();
        } catch (IOException var6) {
        }
          System.out.println(encoding);
    }

附maven依赖

   <dependency>
        <groupId>com.ibm.icu</groupId>
        <artifactId>icu4j</artifactId>
        <version>59.1</version>
   </dependency>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值