我解析mp3标签.
String artist - 我不知道编码是什么
Ïåñíÿ ïðî íàäåæäó - 俄语示例字符串 "????? ??? ???????"
我使用http://code.google.com/p/juniversalchardet/
码:
String GetEncoding(String text) throws IOException {
byte[] buf = new byte[4096];
InputStream fis = new ByteArrayInputStream(text.getBytes());
UniversalDetector detector = new UniversalDetector(null);
int nread;
while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
return encoding;
}
Run Code Online (Sandbox Code Playgroud)
并且隐蔽
new String(text.getBytes(encoding), "cp1251"); - 但这不起作用.
如果我使用utf-16
new String(text.getBytes("UTF-16"), "cp1251") 返回"юяПеснаддодаддуд"space - not is char space
编辑:
这第一个读取字节
byte[] abyFrameData = new byte[iTagSize];
oID3DIS.readFully(abyFrameData);
ByteArrayInputStream oFrameBAIS = new ByteArrayInputStream(abyFrameData);
Run Code Online (Sandbox Code Playgroud)
String s = new String(abyFrameData,"????");
Java 字符串是 UTF-16。所有其他编码都可以使用字节序列表示。要解码字符数据,您必须在第一次创建字符串时提供编码。如果您的字符串已损坏,则为时已晚。
假设 ID3,规范定义了编码规则。例如,ID3v2.4.0可能会限制通过扩展头使用的编码:
q - 文本编码限制
Run Code Online (Sandbox Code Playgroud)0 No restrictions 1 Strings are only encoded with ISO-8859-1 [ISO-8859-1] or UTF-8 [UTF-8].
编码处理在文档下方进一步定义:
如果没有其他说明,字符串(包括数字字符串和 URL)将表示为 $20 - $FF 范围内的 ISO-8859-1 字符。此类字符串在框架描述中表示为
<text string>,或者<full text string>是否允许换行。如果没有其他说明,则禁止换行符。在 ISO-8859-1 中,在允许的情况下仅用 $0A 表示换行符。允许不同类型文本编码的帧包含一个文本编码描述字节。可能的编码:
Run Code Online (Sandbox Code Playgroud)$00 ISO-8859-1 [ISO-8859-1]. Terminated with $00. $01 UTF-16 [UTF-16] encoded Unicode [UNICODE] with BOM. All strings in the same frame SHALL have the same byteorder. Terminated with $00 00. $02 UTF-16BE [UTF-16] encoded Unicode [UNICODE] without BOM. Terminated with $00 00. $03 UTF-8 [UTF-8] encoded Unicode [UNICODE]. Terminated with $00.
使用转码类InputStreamReader或(在这种情况下更有可能)String(byte[],Charset)构造函数来解码数据。另请参阅Java:字符编码粗略指南。
解析 ID3v2.4.0 数据结构的字符串组件将是这样的:
//untested code
public String parseID3String(DataInputStream in) throws IOException {
String[] encodings = { "ISO-8859-1", "UTF-16", "UTF-16BE", "UTF-8" };
String encoding = encodings[in.read()];
byte[] terminator =
encoding.startsWith("UTF-16") ? new byte[2] : new byte[1];
byte[] buf = terminator.clone();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
do {
in.readFully(buf);
buffer.write(buf);
} while (!Arrays.equals(terminator, buf));
return new String(buffer.toByteArray(), encoding);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19275 次 |
| 最近记录: |