user3673296
user3673296

Reputation: 25

Trying to create an 7 GB file size on java

I found this code in order to create a file in a certain size:

    import java.io.*;

    class Test {
    public static void main(String args[]) {
      try {
           RandomAccessFile f = new RandomAccessFile("t", "rw");
           f.setLength(1024 * 1024 * 1024);
      } catch (Exception e) {
           System.err.println(e);
      }
    }
  }

this gives me 1GB, but i want 7 GB, so i did:

   import java.io.*;

   class Test {
   public static void main(String args[]) {
      try {
           RandomAccessFile f = new RandomAccessFile("t", "rw");
           f.setLength(1024 * 1024 * 1024 * 7);
      } catch (Exception e) {
           System.err.println(e);
      }
    }
  }

But i am getting:

java.io.IOException: An attempt was made to move the file pointer before the beginning of the file

Anyone knows what to do?

Upvotes: 2

Views: 624

Answers (1)

Thomas Jungblut
Thomas Jungblut

Reputation: 20969

7GB (in bytes) exceed the 32 bit size of an int. Thus it will overflow to a negative number.

So you need to make it a long:

  f.setLength(1024l * 1024 * 1024 * 7);

Upvotes: 8

Related Questions