在搜索之后使用RandomAccessFile的JAVA非常慢。是什么原因?

时间:2018-05-05 15:24:54

标签: java performance io seek randomaccessfile

这是我的测试代码

long fileSize = 1024 * 1024 * 512L;
byte[] bts = new byte[8];

RandomAccessFile randomAccessFile = new RandomAccessFile("f:/test.data", "rw");
randomAccessFile.setLength(fileSize);

randomAccessFile.seek(0);
long time = System.nanoTime();
randomAccessFile.write(bts);
System.out.println("write1 use:" + (System.nanoTime() - time));

randomAccessFile.seek(1024 * 1024 * 256L);
time = System.nanoTime();
randomAccessFile.write(bts);
System.out.println("write2 use:" + (System.nanoTime() - time));

打印

write1 use:181051
write2 use:2029338072

可以看出,写入是两个9字节,第二次比第一次慢10000倍。

所以我想问为什么搜索会导致文件写得这么慢。有没有解决方案?

1 个答案:

答案 0 :(得分:0)

您要创建一个稀疏文件。 https://en.wikipedia.org/wiki/Sparse_file

final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2);
buf.rewind();

final OpenOption[] options = {
    StandardOpenOption.WRITE,
    StandardOpenOption.CREATE_NEW,
    StandardOpenOption.SPARSE
};
final Path path = Paths.get("/tmp/foo");
Files.deleteIfExists(path);

try (
    final SeekableByteChannel channel
        = Files.newByteChannel(path, options);
) {
    channel.position(1L << 31);
    channel.write(buf);
}

代码取自What is the use of StandardOpenOption.SPARSE?