如何在Channel中有效地转换字符编码?
我需要接受具有不同编码的流并将它们转码为单个预定义编码(例如UTF-8)。我知道怎么用(
InputStream
)Reader
/(OutputStream
)Writer
combo和数组缓冲区来做这个,但这次我正在处理ByteChannel
。当然,我正在研究CharsetDecoder
/CharsetEncoding
解决方案,但我带来的最好的是:
public static void copy(ReadableByteChannel rbc, Charset in,
WritableByteChannel wbc, Charset out) throws IOException {
ByteBuffer b1 = ByteBuffer.allocateDirect(BUFFER_SIZE);
CharBuffer cb = CharBuffer.allocate(BUFFER_SIZE);
ByteBuffer b2 = ByteBuffer.allocateDirect(BUFFER_SIZE);
CharsetDecoder decoder = in.newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPLACE);
CharsetEncoder encoder = out.newEncoder();
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
while( rbc.read(b1)!=-1 ){
b1.flip();
decoder.decode(b1, cb, false);
cb.flip();
encoder.encode(cb, b2, false);
b2.flip();
wbc.write(b2);
b2.compact();
cb.compact();
b1.compact();
}
b1.flip();
while (b1.hasRemaining()){
decoder.decode(b1, cb, true);
cb.flip();
encoder.encode(cb, b2, false);
b2.flip();
wbc.write(b2);
b2.compact();
cb.compact();
}
decoder.decode(b1, cb, true);
decoder.flush(cb);
cb.flip();
while (cb.hasRemaining()){
encoder.encode(cb, b2, true);
b2.flip();
wbc.write(b2);
b2.compact();
}
encoder.encode(cb, b2, true);
encoder.flush(b2);
b2.flip();
while (b2.hasRemaining()){
wbc.write(b2);
}
}
由于这个方法在项目中是“主力”,我必须绝对肯定无论BUFFER_SIZE,编码和阻塞设备的组合是什么,它都会完成。
我的问题是:
是否有更好的缓冲排水方式而不是这些级联的while循环?
是否可以忽略encode()
/decode()
结果(溢出和下溢)?
当然,欢迎任何其他想法。 :)
没有找到相关结果
已邀请:
1 个回复
钾涎净介