Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 27: NIO, Regular Expressions, and Other Packages 821


A second, and often easier, way to read a file is to map it to a buffer. The advantage to
this approach is that the buffer automatically contains the contents of the file. No explicit
read operation is necessary. To map and read the contents of a file, follow this general
procedure. First, open the file usingFileInputStream. Next, obtain a channel to that file by
callinggetChannel( )on the file object. Then, map the channel to a buffer by callingmap( )
on theFileChannelobject. Themap( )method is shown here:


MappedByteBuffer map(FileChannel.MapModehow,
longpos, longsize) throws IOException

Themap( )method causes the data in the file to be mapped into a buffer in memory. The
value inhowdetermines what type of operations are allowed. It must be one of these values:


MapMode.READ_ONLY MapMode.READ_WRITE MapMode.PRIVATE

For reading a file, useMapMode.READONLY. To read and write, useMapeMode.READ
WRITE.MapMode.PRIVATEcauses a private copy of the file to be made, and changes to
the buffer do not affect the underlying file. The location within the file to begin mapping
is specified bypos,and the number of bytes to map are specified bysize.A reference to this
buffer is returned as aMappedByteBuffer, which is a subclass ofByteBuffer. Once the file
has been mapped to a buffer, you can read the file from that buffer.
The following program reworks the first example so that it uses a mapped file:


// Use a mapped file to read a text file.
import java.io.;
import java.nio.
;
import java.nio.channels.*;


public class MappedChannelRead {
public static void main(String args[]) {
FileInputStream fIn;
FileChannel fChan;
long fSize;
MappedByteBuffer mBuf;


try {
// First, open a file for input.
fIn = new FileInputStream("test.txt");

// Next, obtain a channel to that file.
fChan = fIn.getChannel();

// Get the size of the file.
fSize = fChan.size();

// Now, map the file into a buffer.
mBuf = fChan.map(FileChannel.MapMode.READ_ONLY,
0, fSize);
Free download pdf