charset.encode返回结果的疑问
来源:2-11 深入Buffer-Coding-阿里面试题:中文乱码处理和大文件词频统计(1)

慕粉4331336
2021-03-10
按照老师给出的思路,写了用长度有限的Buffer去循环处理中文乱码,在调试过程中发现一个奇怪的事,就是“长坂桥头杀气生,横枪立马眼圆睁。一声好似轰雷震,独退曹家百万兵。”这句话生产的字节数组长达143字节,而且最后有若干个0,比较奇怪。
虽然这么多的0不影响最终结果的输出,但是对这个0比较有疑问
写回答
2回答
-
麻烦再确认下,看上去是buffer没有用完。
152021-03-11 -
求老仙
2021-03-10
分析下:JVM的开发团队不想为每个CharSet都编写一套算法,于是每个字符到底对应几个byte是不确定的,只有一个个转义。 于是就有了下面这段不断分配的程序。
public final ByteBuffer encode(CharBuffer in) throws CharacterCodingException { int n = (int)(in.remaining() * averageBytesPerChar()); ByteBuffer out = ByteBuffer.allocate(n); if ((n == 0) && (in.remaining() == 0)) return out; reset(); for (;;) { CoderResult cr = in.hasRemaining() ? encode(in, out, true) : CoderResult.UNDERFLOW; if (cr.isUnderflow()) cr = flush(out); if (cr.isUnderflow()) break; if (cr.isOverflow()) { n = 2*n + 1; // Ensure progress; n might be 0! ByteBuffer o = ByteBuffer.allocate(n); out.flip(); o.put(out); out = o; continue; } cr.throwException(); } out.flip(); return out; }
112022-08-27
相似问题