java - 查找后使用 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会导致文件写的这么慢。有什么解决办法吗?
解决方案
你想要的是创建一个稀疏文件。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);
}
推荐阅读
- react-native - 无法解压缩文件,因为 react-native 中的 zip 文件中有多个同名文件
- c# - 实体框架在两个不同的上下文中插入实体两次
- c++ - C++ 中缀到后缀转换和计算器
- datepicker - Flutter DatePicker 没有一天
- sql-server - 如何根据不同的列值更新 SQL Server 表
- r - 将 Group by 和 Slope 与 dplyr 一起使用以获取新列
- ios - 为什么我得到不同的结果取决于我在模拟器中使用的是 iPad 还是 iPhone?
- ansible - 超出重试次数时从 async_status 循环中获取有意义的错误消息
- java - 为在 Tomcat 服务器上运行的 java 网站创建 ssl 证书
- javascript - 如何在 Node.js 中获取 URL 参数的值?