Is there an efficient way to create a file with a given size in Java?
In C it can be done with ftruncate (see that answer).
Most people would just write n dummy bytes into the file, but there must be a faster way. I’m thinking of ftruncate and also of Sparse files…
Create a new RandomAccessFile and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.
The following program
on a Linux machine will allocate the space using the ftruncate(2)
while on a Solaris machine it will use the the F_FREESP64 function of the fcntl(2) system call.
In both cases this will result in the creation of a sparse file.