Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
FileChannel fChan;
long fSize;
ByteBuffer mBuf;

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

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

// Now, get the file's size.
fSize = fChan.size();

// Allocate a buffer of the necessary size.
mBuf = ByteBuffer.allocate((int)fSize);

// Read the file into the buffer.
fChan.read(mBuf);

// Rewind the buffer so that it can be read.
mBuf.rewind();

// Read bytes from the buffer.
for(int i=0; i < fSize; i++)
System.out.print((char)mBuf.get());

System.out.println();

fChan.close(); // close channel
fIn.close(); // close file
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}

Here is how the program works. First, a file is opened by using theFileInputStream
constructor, and a reference to that object is assigned tofIn. Next, a channel connected to
the file is obtained by callinggetChannel( )onfIn, and the size of the file is obtained by
callingsize( ). The program then calls theallocate( )method ofByteBufferto allocate a
buffer that will hold the contents of the file when it is read. A byte buffer is used because
FileChanneloperates on bytes. A reference to this buffer is stored inmBuf. The contents
of the file are then read intomBufthrough a call toread( ). Next, the buffer is rewound
through a call torewind( ). This call is necessary because the current position is at the end
of the buffer after the call toread( ). It must be reset to the start of the buffer in order for the
bytes inmBufto be read by callingget( ). BecausemBufis a byte buffer, the values returned
byget( )are bytes. They are cast tocharso that the file can be displayed as text. (Alternatively,
it is possible to create a buffer that encodes the bytes into characters, and then reads that buffer.)
The program ends by closing the channel and the file.

820 Part II: The Java Library

Free download pdf