liwei2633
liwei2633

Reputation: 81

JAVA using RandomAccessFile after seek is very slow. What is the reason?

This is my test code

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));

print

write1 use:181051
write2 use:2029338072

It can be seen that writing is 9 bytes twice and the second time is 10000 times slower than the first time.

So I would like to ask why the seek will cause the file to write so slowly. Is there any solution?

Upvotes: 4

Views: 2900

Answers (1)

Darwin
Darwin

Reputation: 4786

What you want is to create a sparse file. 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);
}

The code was taken from What is the use of StandardOpenOption.SPARSE?

Upvotes: 1

Related Questions