【发布时间】:2012-02-29 00:18:23
【问题描述】:
我正在尝试使用 java 中的字符集 GB2312 解码一个字符 ·
GB2312中包含的这个char,位置码是a1a4check here
代码:
public static void main(String[] _args) throws Exception {
String str="a1a4:· a5f6:ヶ a8c5:ㄅ";
ByteBuffer bf=readToByteBuffer(new ByteArrayInputStream(str.getBytes()));
System.out.println(Charset.forName("GB2312").decode(bf).toString());
}
private static final int bufferSize = 0x20000;
static ByteBuffer readToByteBuffer(InputStream inStream) throws IOException {
byte[] buffer = new byte[bufferSize];
ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);
int read;
while (true) {
read = inStream.read(buffer);
if (read == -1)
break;
outStream.write(buffer, 0, read);
}
ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray());
return byteData;
}
上面的代码输出结果为:
a1a4:? a5f6:ヶ a8c5:ㄅ
我不明白为什么不能解码a1a4?
【问题讨论】:
-
我假设
IO.string2InputStream(d)也使用 GB2312 字符集进行写入。你检查过缓冲区中的字节是否正确吗? -
@RussellZahniser 对此感到抱歉,编辑了我的问题。
-
您可能想做
str.getBytes("GB2312")- 您使用的是默认值,可能是UTF8。但我认为 seh 认为它是一个字符问题而不是编码问题是正确的。
标签: java encoding character-encoding encode