Highlight a large file.

I need to allocate a file about 50 gigabytes in size, but this code:

RandomAccessFile out = new RandomAccessFile("C:\\hello.txt", "rw"); out.setLength(50 * 1024 * 1024 * 1024); // 50 giga-bytes 

Throws an 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 to the beginning of the file.

When I try to allocate 50 megabytes, this exception does not throw. Free disk space is much larger than the required file size.

+6
source share
1 answer

You need to define the size as long using the suffix L :

 out.setLength(50L * 1024L * 1024L * 1024L); 

The problem is that by default, numeric literals are of type int , and 50G is outside its range, so the result of overflow is multiplied. The actual value passed to setLength() is -2147483648 .

In more detail, the type of multiplication result (as well as other numerical operations) is determined by its most common operand, so you actually do not need to add the suffix L to each of them. It is enough to add it only to them (the first is a reasonable choice):

 long wrong = 50 * 1024 * 1024 * 1024; // -2147483648 long right = 50L * 1024 * 1024 * 1024; // 53687091200 
+9
source

Source: https://habr.com/ru/post/979935/


All Articles