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

I want to create a file containing random bits in Java. What will create the random file the fastest? I want to create files of any given size containing random bits. I want to be able to generate a 2 GB file in minutes (less than a minute if possible). The technique I'm using now takes several hours to make 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 must be a way to do this faster, maybe even in less than a minute for 2 GB.

Thanks.

+4
source share
2 answers

If you want to generate random bits right away, rather than looping around , look at the java.util.Random method nextBytes (byte []) , which populates the specified byte array with random bytes. Create an array of bytes large enough for 2GiB data, and you can generate an entire random source of bits at a time.

+6
source

Try wrapping the FileOutputStream file with BufferedOutputStream.

+3
source

All Articles