Java Reference
In-Depth Information
You could also have used the
read()
method that accepts a single argument together with the
posi-
tion()
method:
for(int i = 0 ; i<PRIMESREQUIRED ; ++i) {
index = LONG_BYTES*(int)(PRIMECOUNT*Math.random());
inCh.position(index).read(buf);
// Read the value
buf.flip();
primes[i] = buf.getLong(); // Save it in the
array
buf.clear();
}
Calling the
position()
method sets the file position to
index
then the
read()
method reads the file
starting at that point.
The need to be able to access and update a file randomly arises quite often. Even with a simple personnel
file, for example, you are likely to need the capability to update the address or the phone number for an
individual. Assuming you have arranged for the address and phone number entries to be of a fixed length,
you could update the data for any entry simply by overwriting it. If you want to read from and write to
the same file you can just open the channel for reading and writing. Let's try that, too.
TRY IT OUT: Reading and Writing a File Randomly
You can modify the previous example so that you overwrite each random prime that you retrieve from
the
primes_backup.bin
file that you created earlier with the value
99999L
to make it stand out from the
rest. This messes up the
primes_backup.bin
file that you use here, but you can always run the program
that copies files to copy
primes.bin
if you want to restore it. Here's the code:
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.SeekableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumSet;
public class RandomReadWrite {
public static void main(String[] args)
{
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("primes_backup.bin");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating
program.");
System.exit(1);
}