java写一段程序,自动检测文件的字符集并返回

下面是使用 Java 语言检测文件字符集的一个示例程序:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.mozilla.universalchardet.UniversalDetector;

public class DetectFileEncoding {

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.err.println("Usage: java DetectFileEncoding <file>");
            System.exit(1);
        }

        String fileName = args[0];
        byte[] buf = new byte[4096];

        // 创建字符集检测器
        UniversalDetector detector = new UniversalDetector(null);

        // 打开文件
        BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileName));

        // 使用字符集检测器检测文件的字符集
        int nread;
        while ((nread = input.read(buf)) > 0 &amp;&amp; !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }
        detector.dataEnd();

        // 获取检测到的字符集
        String encoding = detector.getDetectedCharset();
        if (encoding != null) {
            System.out.println("Detected encoding = " + encoding);
        } else {
            System.out.println("No encoding detected.");
        }

        // 关闭文件
        input.close();
    }
}