我想使用 ByteBuffer
对 channel 执行 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);
问题是:哪种方法的性能和吞吐量最高?
最佳答案
您为什么要使用 compact()
? - 它可能涉及重复复制大量数据。
如果您没有充分的理由在写入所有先前读取的数据之前执行另一次读取,那么您可以采用第一种方法。
哦,顺便说一下:如果您只是想将数据从一个文件复制到另一个文件,请查看 transferTo()
, 或 transferFrom()
.这是文件复制的最高性能方式,因为这可能使用底层操作系统的非常高效的操作,例如 DMA。
(编辑:transferTo() 等。当然不需要需要任何 ByteBuffer,混合两种想法:))
关于java - 使用 ByteBuffer 在 channel 上进行 I/O 操作 - 性能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7944438/