javarandombytebit

What is the fastest way to create a 2GB file containing random bytes in Java?


I want a way to generate a file containing random bits in Java. What will create the random file the fastest? I want to create files of any specified size containing random bits. I want to be able to generate a 2GB file in a matter of minutes (less than a minute if possible). The technique I'm using right now takes hours to do 2GB:

...
private static Random r = new Random();

private static int rand(int lo, int hi) {
    int n = hi - lo + 1;
    int i = r.nextInt() % n;
    if (i < 0) {
        i = -i;
    }
    return lo + i;
}
...
fos = new FileOutputStream(hdFiller);
for(long i = 0; i < maxFileSize; i++) {
    int idx = rand(0,32);
    fos.write(idx);
}
fos.close();
...

There has got to be a way to do this faster, maybe even in less than a minute for 2GB.

Thanks.


Solution

  • If you want to generate random bits all at once, rather than looping, take a look at the java.util.Random method nextBytes(byte[]) which fills the specified byte array with random bytes. Create a byte array exactly large enough for 2GiB of data and you can generate the whole random bit source in one go.