Java Reference
In-Depth Information
// Read the number of random primes required
for(int i = 0 ; i < PRIMESREQUIRED ; ++i) {
index = LONG_BYTES*(int)(PRIMECOUNT*Math.random());
inCh.read(buf, index);
// Read the value
buf.flip();
primes[i] = buf.getLong();
// Save it in the array
buf.clear();
}
// Output the selection of random primes 5 to a line in field
width of 12
int count = 0;
// Count of primes written
for(long prime : primes) {
System.out.printf("%12d", prime);
if(++count%5 == 0) {
System.out.println();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
RandomFileRead.java
When I ran this, I got the following output:
359 107 383 109 7
173 443 337 17 113
You should get something similar but not the same because the random number generator is seeded using
the current clock time. The number of random selections is fixed, but you could easily add code for a
value to be entered on the command line.
How It Works
You access a random prime in the file by generating a random position in the file with the expression
8*(int)(PRIMECOUNT*Math.random()) . The value of index is a pseudo-random integer that can be
from 0 to the number of primes in the file minus one, multiplied by 8 because each prime occupies 8
bytes. The prime is read from the file with the statement:
inCh.read(buf, index); // Read the value at index
This calls the read() method for the channel object that accepts a file position argument to specify from
where in the file bytes are to be read. Because buf has a capacity of 8 bytes, only one prime is read each
time. You store each randomly selected prime in an element of the primes array.
Finally, you output the primes five to a line in a field width of 12 characters.
Search WWH ::




Custom Search