我正在使用java.nio.channels.FileChannel
将数据写入文件。这是我的代码:
RandomAccessFile raf = new RandomAccessFile(file, "rws");
FileChannel fileChannel = raf.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
long offset = 0;
while (offset < 1024 * 1024 * 1024) {
buffer.clear();
fileChannel.write(buffer, offset);
buffer.clear();
offset += buffer.remaining();
logger.warn("fake write {} {}", offset, buffer.remaining());
}
我的出局就像:
WARN [11:01:58,498][writer]BackUp(151):fake write 3047424 4096
WARN [11:01:58,507][writer]BackUp(151):fake write 3051520 4096
WARN [11:01:58,515][writer]BackUp(151):fake write 3055616 4096
WARN [11:01:58,523][writer]BackUp(151):fake write 3059712 4096
WARN [11:01:58,532][writer]BackUp(151):fake write 3063808 4096
WARN [11:01:58,540][writer]BackUp(151):fake write 3067904 4096
WARN [11:01:58,549][writer]BackUp(151):fake write 3072000 4096
WARN [11:01:58,557][writer]BackUp(151):fake write 3076096 4096
WARN [11:01:58,565][writer]BackUp(151):fake write 3080192 4096
WARN [11:01:58,574][writer]BackUp(151):fake write 3084288 4096
WARN [11:01:58,582][writer]BackUp(151):fake write 3088384 4096
WARN [11:01:58,590][writer]BackUp(151):fake write 3092480 4096
WARN [11:01:58,599][writer]BackUp(151):fake write 3096576 4096
WARN [11:01:58,607][writer]BackUp(151):fake write 3100672 4096
WARN [11:01:58,615][writer]BackUp(151):fake write 3104768 4096
WARN [11:01:58,624][writer]BackUp(151):fake write 3108864 4096
WARN [11:01:58,632][writer]BackUp(151):fake write 3112960 4096
你可以看到我按顺序写作,但每 4K 费用 8 ms, 500 KB / s 。这很慢,我真的很困惑。