// Read bytes from the buffer.
for(int i=0; i < fSize; i++)
System.out.print((char)mBuf.get());
fChan.close(); // close channel
fIn.close(); // close file
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}
As before, the file is opened by using theFileInputStreamconstructor, and a reference
to that object is assigned tofIn. A channel connected to the file is obtained by calling
getChannel( )onfIn, and the size of the file is obtained. Then the entire file is mapped into
memory by callingmap( ), and a reference to the buffer is stored inmBuf. The bytes inmBuf
are read by callingget( ).
Writing to a File
There are several ways to write to a file through a channel. Again, we will look at two. First,
you can write data to an output file through a channel, by using explicit write operations.
Second, if the file is opened for read/write operations, you can map the file to a buffer and
then write to that buffer. Changes to the buffer will automatically be reflected in the file.
Both ways are described here.
To write to a file through a channel using explicit calls towrite( ), follow these steps.
First, open the file for output. Next, allocate a byte buffer, put the data you want to write
into that buffer, and then callwrite( )on the channel. The following program demonstrates
this procedure. It writes the alphabet to a file calledtest.txt.
// Write to a file using NIO.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ExplicitChannelWrite {
public static void main(String args[]) {
FileOutputStream fOut;
FileChannel fChan;
ByteBuffer mBuf;
try {
fOut = new FileOutputStream("test.txt");
// Get a channel to the output file.
fChan = fOut.getChannel();
// Create a buffer.
mBuf = ByteBuffer.allocateDirect(26);
822 Part II: The Java Library