Java检测文件编码

Java程序在处理文件时,若不指定编码格式可能导致中文乱码。本文介绍如何使用第三方库juniversalchardet来检测文件编码,以避免乱码问题。尽管编码检测准确度有待验证,但该方法提供了一种解决途径。

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

Java检测文件编码

在Demo中涉及到文件的读写操作,但是在程序中并不知道文件的编码格式,文件的编码格式有UTF8,GBK等,如果不指定固定的编码格式的话,会默认采用系统编码,如果原文件为GBK编码且包含中文,而采用UTF-8编码字节流向字符流读入则会中文乱码,

BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(new FileInputStream(
                "./users.csv"), "指定源文件的编码格式"));

所以需要通过代码判断文件的编码格式;
这里使用了第三方工具包juniversalchardet
地址上有相应的说明,

maven依赖

<dependency>
    <groupId>com.googlecode.juniversalchardet</groupId>
    <artifactId>juniversalchardet</artifactId>
    <version>1.0.3</version>
</dependency>

public static String getCharset(InputStream is) {

    UniversalDetector detector = new UniversalDetector(null);
    try {
        byte[] bytes = new byte[1024];
        int nread;
        if ((nread = is.read(bytes)) > 0 && !detector.isDone()) {
            detector.handleData(bytes, 0, nread);
        }
    } catch (Exception localException) {
        log.info("detected code:", localException);
    }
    detector.dataEnd();
    String encode = detector.getDetectedCharset();
    /** default UTF-8 */
    if (StringUtils.isEmpty(encode)) {
        encode = "UTF-8";
    }
    detector.reset();
    return encode;
    }

public static void main(String[] args) {
    File file = new File("file path");
    InputStream is = new FileInputStream(file);
    getCharset(is); 
}

编码格式检测的准确度有待验证。


附录:
https://stackoverflow.com/questions/1677497/guessing-the-encoding-of-text-represented-as-byte-in-java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值