Java判断一个文件原来的编码方式

本文介绍如何使用ICU4J库在Java中检测文件的字符编码方式。通过Maven引入ICU4J依赖,实现了一个JudgeFileCharset类,该类提供了静态方法用于读取文件并返回其编码类型。若检测失败或编码为空,则默认为UTF-8。

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

第一步,引入maven

 <!--Charset获取文件原来编码方式的-->
 <dependency> 
	 <groupId>com.ibm.icu</groupId> 
	 <artifactId>icu4j</artifactId> 
	 <version>59.1</version> 
 </dependency>

第二步代码

package com.hzt.controller.test;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JudgeFileCharset {
    private static Logger logger = Logger.getLogger(JudgeFileCharset.class);

    public JudgeFileCharset() {
    }
    
    public static String 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) {
                return encoding;
            }

            encoding = match.getName();
        } catch (IOException var6) {
            logger.error(var6.getMessage());
        }

        return encoding;
    }
}



第三,要注意
编码方式有可能为空,这个时候手动设置你想要的编码方式

String charset = JudgeFileCharset.getFileCharsetByICU4J(file); 
if(StringUtils.isNullOrEmpty(charset)){ 
	charset="UTF-8"; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值