gpt4 book ai didi

android - Android 中的字符集检测

转载 作者:太空狗 更新时间:2023-10-29 16:42:28 24 4
gpt4 key购买 nike

我的 Android 应用程序检索 SHOUTcast 元数据并显示它。我遇到了非英语字符集问题。基本上,元数据显示为乱码。我将如何执行字符编码检测并正确显示文本?抱歉,如果这是一个不平凡的问题,我对这个话题不是很精通。

有问题的流是:http://skully.hopto.org:8000

最佳答案

正如 vorrtex 在他上面的评论中指出的那样,如果您的数据以格式良好的 HTML 代码形式出现,您可以从 <meta content="..."> 知道它的编码。标签,这是最好的场景。您可以使用如下代码将其转换为 Android(或其他 Java 实现)字符串:

// assume you have your input data as byte array buf, and encoding
// something like "windows-1252", "UTF-8" or whatever
String str = new String(buf, encoding);
// now your string will display correctly

如果您不知道编码 - 您收到的数据是未知格式的原始文本 - 您仍然可以使用统计语言模型尝试算法来猜测它。我刚刚在 http://site.icu-project.org/ 找到了 IBM 的 ICU - Unicode 国际组件 项目,具有自由开源许可(商业用途 OK)

它们同时提供 Java 和 C++ 库。我刚刚添加了他们的 Java JAR 版本。 51.2 到我的 Android 项目,它工作得很好。我用来从文本文件中识别字符编码的代码是:

public static String readFileAsStringGuessEncoding(String filePath)
{
String s = null;
try {
File file = new File(filePath);
byte [] fileData = new byte[(int)file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();

CharsetMatch match = new CharsetDetector().setText(fileData).detect();

if (match != null) try {
Lt.d("For file: " + filePath + " guessed enc: " + match.getName() + " conf: " + match.getConfidence());
s = new String(fileData, match.getName());
} catch (UnsupportedEncodingException ue) {
s = null;
}
if (s == null)
s = new String(fileData);
} catch (Exception e) {
Lt.e("Exception in readFileAsStringGuessEncoding(): " + e);
e.printStackTrace();
}
return s;
}
上面的

Lt.dLt.e 只是我对 Log.d(TAG, "blah...") 的快捷方式.在我能想到的所有测试文件上都运行良好。我有点只关心 APK 文件大小——icu4j-51_2.jar 超过 9 MB,而我的整个包在添加它之前只有 2.5 MB。但是隔离 CharsetDetector 及其依赖项很容易,所以我最后添加的大小不超过 50 kB。我需要从 ICU 源代码复制到我的项目的 Java 类都在 core/src/com/ibm/icu/text 目录下,它们是:

CharsetDetector
CharsetMatch
CharsetRecog_2022
CharsetRecog_mbcs
CharsetRecog_sbcs
CharsetRecog_Unicode
CharsetRecog_UTF8
CharsetRecognizer

此外,在 CharsetRecog_sbcs.java 中还有一个 protected “ArabicShaping as;”成员,它想要拉出更多的类,但事实证明对于字符集识别来说不需要它,所以我把它注释掉了。就这样。希望对您有所帮助。

格雷格

关于android - Android 中的字符集检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com