// Write some bytes to the buffer.
for(int i=0; i<26; i++)
mBuf.put((byte)('A' + i));
// Rewind the buffer so that it can be written.
mBuf.rewind();
// Write the buffer to the output file.
fChan.write(mBuf);
// close channel and file.
fChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}
The call torewind( )onmBufis necessary in order to reset the current position to zero after
data has been written tomBuf. Remember, each call toput( )advances the current position.
Therefore, it is necessary for the current position to be reset to the start of the buffer before
callingwrite( ). If this is not done,write( )will think that there is no data in the buffer.
To write to a file using a mapped file, follow these steps. First, open the file for read/write
operations. Next, map that file to a buffer by callingmap( ). Then, write to the buffer. Because
the buffer is mapped to the file, any changes to that buffer are automatically reflected in the file.
Thus, no explicit write operations to the channel are necessary. Here is the preceding program
reworked so that a mapped file is used. Notice that the file is opened as aRandomAccessFile.
This is necessary to allow the file to be read and written.
// Write to a mapped file.
import java.io.;
import java.nio.;
import java.nio.channels.*;
public class MappedChannelWrite {
public static void main(String args[]) {
RandomAccessFile fOut;
FileChannel fChan;
ByteBuffer mBuf;
try {
fOut = new RandomAccessFile("test.txt", "rw");
// Next, obtain a channel to that file.
fChan = fOut.getChannel();
// Then, map the file into a buffer.
mBuf = fChan.map(FileChannel.MapMode.READ_WRITE,
0, 26);
Chapter 27: NIO, Regular Expressions, and Other Packages 823