首页 > 解决方案 > 查找后使用 RandomAccessFile 的 JAVA 非常慢。是什么原因?

问题描述

这是我的测试代码

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倍。

所以想问一下为什么seek会导致文件写的这么慢。有什么解决办法吗?

标签: javaperformanceioseekrandomaccessfile

解决方案


你想要的是创建一个稀疏文件。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?


推荐阅读