// Write some bytes to the buffer.
for(int i=0; i<26; i++)
mBuf.put((byte)('A' + i));
// close channel and file.
fChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}
As you can see, there are no explicit write operations to the channel itself. Because mBuf
is mapped to the file, changes to mBuf are automatically reflected in the underlying file.
Copying a File Using NIO
NIO simplifies some types of file operations. For example, the following program copies a
file. It does so by opening an input channel to the source file and an output channel to the
target file. It then writes the mapped input buffer to the output file in a single operation. You
might want to compare this version of the file copy program to the one found in Chapter 13.
As you will find, the part of the program that actually copies the file is substantially shorter.
// Copy a file using NIO.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class NIOCopy {
public static void main(String args[]) {
FileInputStream fIn;
FileOutputStream fOut;
FileChannel fIChan, fOChan;
long fSize;
MappedByteBuffer mBuf;
try {
fIn = new FileInputStream(args[0]);
fOut = new FileOutputStream(args[1]);
// Get channels to the input and output files.
fIChan = fIn.getChannel();
fOChan = fOut.getChannel();
// Get the size of the file.
fSize = fIChan.size();
// Map the input file to a buffer.
mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY,
0, fSize);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home