我正在尝试使用 RandomAccessFile.setLength() 方法编写文件。我遇到的问题是:它适用于某些文件大小,但不适用于其他文件大小。
疯狂猜测:我不确定这是否与我的 RAM(16GB)有关?AFAIK 对于 8 的倍数的大 GB 值似乎失败了。
如果有人知道为什么会发生这种情况,那将是最好的答案。
我包含了一个玩具程序,它应该展示这种行为。如果您看到相同的结果,请告诉我。
import java.io.*;
public class Debug {
public static void main( String[] args ) {
// create 5 file sizes: 16 KB, 16 MB, 8GB, 16 GB, 30 GB
long KILO = 1024;
long testNum1 = KILO * 16; // 16 KB
long testNum2 = KILO * KILO * 16; // 16 MB
long testNum3 = KILO * KILO * KILO * 8; // 8 GB
long testNum4 = KILO * KILO * KILO * 16; // 16 GB
long testNum5 = KILO * KILO * KILO * 30; // 30 GB
// print the 5 file sizes
System.out.println("testNum1 is " + testNum1 + " bytes");
System.out.println("testNum2 is " + testNum2 + " bytes");
System.out.println("testNum3 is " + testNum3 + " bytes");
System.out.println("testNum4 is " + testNum4 + " bytes");
System.out.println("testNum5 is " + testNum5 + " bytes");
// attempt to write 5 files to disk, using these sizes
RandomAccessFile f = null;
try {
f = new RandomAccessFile("testNum1", "rw"); // <-- PASS
f.setLength( testNum1 );
f = new RandomAccessFile("testNum2", "rw"); // <-- PASS
f.setLength( testNum2 );
f = new RandomAccessFile("testNum3", "rw"); // <-- FAIL
f.setLength( testNum3 );
f = new RandomAccessFile("testNum4", "rw"); // <-- FAIL
f.setLength( testNum4 );
f = new RandomAccessFile("testNum5", "rw"); // <-- PASS
f.setLength( testNum5 );
} catch( Exception e ) {
System.err.println(e);
} finally {
if( f != null ) {
try {
f.close();
} catch( IOException e ) {
e.printStackTrace();
}
}
}
}
}