gpt4 book ai didi

JAVA 在查找后使用 RandomAccessFile 非常慢。是什么原因?

转载 作者:行者123 更新时间:2023-12-05 06:34:34 25 4
gpt4 key购买 nike

这是我的测试代码

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会导致文件写的这么慢。有什么解决办法吗?

最佳答案

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

关于JAVA 在查找后使用 RandomAccessFile 非常慢。是什么原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com