Create a huge dummy file in Java in an instant
To create a file of arbitrary size without really ‘writing it’, which can take quite some time for huge files, you can use java.io.RandomAccessFile
.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RunnableExample {
public static void main(String[] args) throws IOException {
// Create a file with 1 GB size
createFileWithSize(new File("/Users/kaimechel/temp"), "dummyFile", 1L * 1024L * 1024L * 1024L);
}
public static File createFileWithSize(File parentFolder, String filename, long size) throws IOException {
File file = new File(parentFolder, filename);
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
raf.setLength(size);
}
return file;
}
}