![](/img/trans.png)
[英]accessing HBase using Java API, the first connection is very slow. Is it normal?
[英]JAVA using RandomAccessFile after seek is very slow. What is the reason?
這是我的測試代碼
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.