I need allocate file with size near 50 gigabytes, but this code:
RandomAccessFile out = new RandomAccessFile("C:\\hello.txt", "rw");
out.setLength(50 * 1024 * 1024 * 1024); // 50 giga-bytes
Throws exception:
Exception in thread "main" java.io.IOException: Попытка поместить указатель на файл перед началом файла
at java.io.RandomAccessFile.setLength(Native Method)
at Experiment.main(Experiment.java:8)
: Attempting to move the file pointer before the beginning of the file.
When I trying allocate 50 megabytes such exception not throws. Free space of disk is much greater then needed file size.
Open up Windows Task Manager, find the biggest process you have running right click, and click on Create dump file . This will create a file relative to the size of the process in memory in your temporary folder. You can easily create a file sized in gigabytes.
You need to define the size as a long
by using the L
suffix:
out.setLength(50L * 1024L * 1024L * 1024L);
The problem is that by default, numeric literals are of int
type and 50G is outside of its range, so the result of the multiplication overflows. The actual value passed to the setLength()
is -2147483648
.
In more detail, the result type of multiplication (as well as other numeric operations) is defined by the most general of its operands, so you don't actually need to add the L
suffix to every one of them. It is sufficient to add it to only just of them (the first one is a sensible choice):
long wrong = 50 * 1024 * 1024 * 1024; // -2147483648
long right = 50L * 1024 * 1024 * 1024; // 53687091200
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With