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.
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.
Try wrapping your FileOutputStream with a BufferedOutputStream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With