我的安卓应用程序获取SHOUTcast元数据并将其显示出来。我遇到了一个使用非英文字符集时显示乱码的问题。请问如何检测字符编码并正确地显示文本?不好意思,如果这是一个非常复杂的问题,我对这个主题并不熟悉。
相关流媒体地址为:http://skully.hopto.org:8000
我的安卓应用程序获取SHOUTcast元数据并将其显示出来。我遇到了一个使用非英文字符集时显示乱码的问题。请问如何检测字符编码并正确地显示文本?不好意思,如果这是一个非常复杂的问题,我对这个主题并不熟悉。
相关流媒体地址为:http://skully.hopto.org:8000
<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
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.d和Lt.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
<meta content="text/html; charset=windows-1252" http-equiv="Content-Type">
。这意味着编码是Windows-1252,如果您只使用此站点,则可以硬编码此编码名称并始终使用它。 - vortexwolf