猜测在 Java 中表示为 byte[] 的文本的编码 [英] Guessing the encoding of text represented as byte[] in Java

查看:21
本文介绍了猜测在 Java 中表示为 byte[] 的文本的编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以某种未知编码(通常是 UTF-8 或 ISO-8859-1,但不一定如此)表示文本的字节数组,获得最可能使用的编码的猜测的最佳方法是什么(在 Java 中))?

Given an array of bytes representing text in some unknown encoding (usually UTF-8 or ISO-8859-1, but not necessarily so), what is the best way to obtain a guess for the most likely encoding used (in Java)?

值得注意的是:

  • 没有额外的元数据可用.字节数组实际上是唯一可用的输入.
  • 检测算法显然不会 100% 正确.如果算法在超过 80% 的情况下是正确的,那就足够了.

推荐答案

下面的方法使用解决问题juniversalchardet,它是 Mozilla 编码检测库的 Java 端口.

The following method solves the problem using juniversalchardet, which is a Java port of Mozilla's encoding detection library.

public static String guessEncoding(byte[] bytes) {
    String DEFAULT_ENCODING = "UTF-8";
    org.mozilla.universalchardet.UniversalDetector detector =
        new org.mozilla.universalchardet.UniversalDetector(null);
    detector.handleData(bytes, 0, bytes.length);
    detector.dataEnd();
    String encoding = detector.getDetectedCharset();
    detector.reset();
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }
    return encoding;
}

上面的代码已经过测试并且可以正常工作.只需将 juniversalchardet-1.0.3.jar 添加到类路径.

The code above has been tested and works as intented. Simply add juniversalchardet-1.0.3.jar to the classpath.

我测试了 juniversalchardetjchardet.我的总体印象是 juniversalchardet 提供了两个库中更好的检测精度和更好的 API.

I've tested both juniversalchardet and jchardet. My general impression is that juniversalchardet provides the better detection accuracy and the nicer API of the two libraries.

这篇关于猜测在 Java 中表示为 byte[] 的文本的编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆