【发布时间】:2011-12-18 04:04:02
【问题描述】:
我想使用ByteBuffer 对通道执行 I/O 操作。最后我想出了三个解决方案:
FileChannel inChannel = new FileInputStream("input.txt").getChannel();
FileChannel outChannel = new FileOutputStream("output.txt").getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);
方法一:使用hasRemaining()
while (inChannel.read(buf) != -1) {
buf.flip();
while (buf.hasRemaining()) {
outChannel.write(buf);
}
buf.clear();
}
方法二:使用compact()
while (inChannel.read(buf) != -1 || buf.position() > 0) {
buf.flip();
outChannel.write(buf);
buf.compact();
}
方法三:混合模型
while (inChannel.read(buf) != -1) {
buf.flip();
outChannel.write(buf);
buf.compact();
}
// final flush of pending output
while (buf.hasRemaining())
outChannel.write(buf);
问题是:哪种方法的性能和吞吐量最高?
【问题讨论】:
-
这是我想知道的。你对此有什么结论吗?除了给出答案? vanillajava.blogspot.kr/2011/11/…
标签: java performance bytebuffer channels