Java Reference
In-Depth Information
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 we want to read
and write the same file we can just create two file streams and get two file channels for the file, one for
input and one for output. Let's try that too.
Try It Out - Reading and Writing a File Randomly
We can modify the previous example so we overwrite each random prime that we retrieve with the
value 99999L to make it stand out from the rest. This will mess up the primes.bin file but you can
always run the program that created it again if you want to restore it. Here's the code:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class RandomReadWrite {
public static void main(String[] args)
{
File aFile = new File("C:/Beg Java Stuff/primes.bin");
FileInputStream inFile = null;
FileOutputStream outFile = null;
try {
inFile = new FileInputStream(aFile);
outFile = new FileOutputStream(aFile, true);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel inChannel = inFile.getChannel();
FileChannel outChannel = outFile.getChannel();
final int PRIMESREQUIRED = 10;
ByteBuffer buf = ByteBuffer.allocate(8*PRIMESREQUIRED);
long[] primes = new long[PRIMESREQUIRED];
int index = 0; // Position for a prime in the file
final long REPLACEMENT = 99999L; // Replacement for a selected prime
try {
final int PRIMECOUNT = (int)inChannel.size()/8;
System.out.println("Prime count = "+PRIMECOUNT);
for(int i = 0 ; i<PRIMESREQUIRED ; i++) {
index = 8*(int)(PRIMECOUNT*Math.random());
inChannel.read(buf, index);
buf.flip();
primes[i] = buf.getLong();
buf.flip();
buf.putLong(REPLACEMENT);
buf.flip();
Search WWH ::




Custom Search