Java Reference
In-Depth Information
outChannel.write(buf, index);
buf.clear();
}
StringBuffer str = null;
for(int i = 0 ; i<PRIMESREQUIRED ; i++) {
str = new StringBuffer(" ").append(primes[i]);
System.out.print((i%5 == 0 ? "\n" : "")
+ str.substring(str.length()-12, str.length()));
}
inFile.close(); // Close the file and the channel
outFile.close();
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
This will produce a set of ten random prime selections from the file. If you want to verify that we have
indeed overwritten these values in the file you can run the ReadPrimes example that we wrote earlier
in this chapter.
How It Works
All we had to do to write the file as well as read it was to create a FileOutputStream object for the
file in addition to the FileInputStream object and access its file channel. We are then able to use
one channel for writing to the file and the other for reading it. We can read and write sequentially or at
random. The channel read() and write() methods we are using here explicitly specify the position
where the data is to be read or written as an argument. In this case the file position recorded by the
channel does not change. We could equally well change the file position for the channel before
performing the read or write, like this:
for(int i = 0 ; i<PRIMESREQUIRED ; i++) {
index = 8*(int)(PRIMECOUNT*Math.random());
inChannel.position(index); // Set the file position
inChannel.read(buf); // and read from the file
buf.flip();
primes[i] = buf.getLong();
buf.flip();
buf.putLong(REPLACEMENT);
buf.flip();
outChannel.position(index); // Set the file position
outChannel.write(buf); // and write to the file
buf.clear();
}
Search WWH ::




Custom Search