我試圖用charset解碼器逐字節地解碼UTF8。這可能嗎?使用charset解碼器以逐字節的方式解碼多字節UTF8符號?
以下代碼
public static void main(String[] args) {
Charset cs = Charset.forName("utf8");
CharsetDecoder decoder = cs.newDecoder();
CoderResult res;
byte[] source = new byte[] {(byte)0xc3, (byte)0xa6}; // LATIN SMALL LETTER AE in UTF8
byte[] b = new byte[1];
ByteBuffer bb = ByteBuffer.wrap(b);
char[] c = new char[1];
CharBuffer cb = CharBuffer.wrap(c);
decoder.reset();
b[0] = source[0];
bb.rewind();
cb.rewind();
res = decoder.decode(bb, cb, false);
System.out.println(res);
System.out.println(cb.remaining());
b[0] = source[1];
bb.rewind();
cb.rewind();
res = decoder.decode(bb, cb, false);
System.out.println(res);
System.out.println(cb.remaining());
}
給出以下輸出。
UNDERFLOW
1
MALFORMED[1]
1
爲什麼?
@jlordo這些原因在這個問題上是不重要的 – 2013-02-09 23:21:36