RandomAccessFile setLength()为大千兆字节值写入0

时间:2014-01-20 04:49:56

标签: java randomaccessfile

我正在尝试使用RandomAccessFile.setLength()方法编写文件。我遇到的问题是: 它适用于某些文件大小但不适用于其他文件。

狂野猜测:我不确定它是否与我的RAM(16GB)有关? AFAIK似乎没有大的GB值,它是8的倍数。

如果有人知道为什么这实际上是最好的答案。

我加入了一个应该证明这种行为的玩具程序。如果你看到相同的结果,请告诉我。

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();
        }
      }
    }
  }

}

0 个答案:

没有答案