我需要接受具有不同编码的流,并将它们转换为单个预定义编码(例如,UTF-8)。我知道如何使用(InputStream)Reader / (OutputStream)Writer组合体和数组缓冲区来实现这一点,但这一次我要处理的是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、编码和阻塞设备的任何组合,我都必须绝对确定它将完成输出。
我的问题是:
underflows)?:
encode() / decode()结果(对于溢出和当然,任何其他想法都是受欢迎的。:)
发布于 2013-03-12 22:31:04
要提高上述代码的性能:
缓冲区大小的4倍,字符可以是1-4字节。此外,将字节缓冲区分配为页面大小的倍数(通常为4k)可以帮助IO performance.。
最重要的是,用真实的数据编写一个基准,并使用它作为衡量性能改进的一种手段。如果你不测量,你就永远不会知道什么起作用了。
https://stackoverflow.com/questions/5624847
复制相似问题