Java Reference
In-Depth Information
We now create a pair of file stream objects to work with:
FileInputStream inFile = null;
FileOutputStream outFile = null;
try {
inFile = new FileInputStream(fromFile);
outFile = new FileOutputStream(toFile);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
assert false;
}
Since we checked the File objects, we know we won't see a FileNotFoundException being thrown
but we still must provide for the possibility. Of course, the FileInputStream object corresponds to
the file name entered on the command line. Creating the FileOutputStream object will result in a
new empty file being created, ready for loading with the data from the input file.
Next we get the channel for each file from the file streams:
FileChannel inChannel = inFile.getChannel();
FileChannel outChannel = outFile.getChannel();
Once we have the channel objects we transfer the contents of the input file to the output file like this:
try {
int bytesWritten = 0;
long byteCount = inChannel.size();
while(bytesWritten<byteCount)
bytesWritten += inChannel.transferTo(bytesWritten,
byteCount-bytesWritten,
outChannel);
System.out.println("File copy complete. " + byteCount
+ " bytes copied to " + toFile.getAbsolutePath());
inFile.close();
outFile.close();
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
The data is copied using the transferTo() method for inChannel . You could equally well use the
transferFrom() method for outChannel . The chances are the transferTo() method will
transfer all the data in one go. The while loop is there just in case it doesn't. The loop condition checks
whether the number of bytes written is less than the number of bytes in the file. If it is, the loop
executes another transfer operation for the number of bytes left in the file with the file position specified
as the number of bytes written so far.
Search WWH ::




Custom Search