Java Reference
In-Depth Information
AsynchronousCloseException
Thrown if either channel is closed by another thread
while the operation is in progress.
ClosedByInterruptException
Thrown if another thread interrupts the current thread
while the operation is in progress.
IOException
Thrown if some other I/O error occurs.
The value of these methods lies in the potential for using the I/O capabilities of the underlying
operating system directly. Where this is possible, the operation is likely to be much faster than copying
from one file to another in a loop using the read() and write() methods we have seen.
A file copy program is an obvious candidate for trying out these methods.
Try It Out - Direct Data Transfer between Channels
We will put together a program that will copy the file that is specified by a command line argument. We
will copy the file to a backup file that we will create in the same directory as the original. We will create
the name of the new file by appending " _ backup" to the original file name as many times as necessary
to form a unique file name. That operation is a good candidate for writing a helper method:
// Method to create a unique backup File object
public static File createBackupFile(File aFile) {
aFile = aFile.getAbsoluteFile(); // Ensure we have an absolute path
File parentDir = new File(aFile.getParent()); // Get the parent directory
String name = aFile.getName(); // Get the file name
int period = name.indexOf('.'); // Find the extension separator
if(period == -1) // If there isn't one
period = name.length(); // set it to the end of the string
String nameAdd = " _ backup"; // String to be appended
// Create a File object that is unique
File backup = new File(name.substring(0,period) + nameAdd
+ name.substring(period));
while(backup.exists()) { // If the name already exists...
name = backup.getName(); // Get the current name of the file
period += nameAdd.length(); // Increment separator index
backup = new File(parentDir,name.substring(0,period) // add _ backup again
+ nameAdd + name.substring(period));
}
return backup;
}
This method assumes the argument has already been validated as a real file. After making sure that aFile is
not a relative path we extract the basic information we need to create the new file - the parent directory, the
file name, and where the period separator is, if there is one. We then create a File object using the original
file name with "_ backup " appended. The while loop will execute as long as the name already exists as a
file, and will append further instances of " _ backup" until a unique file name is arrived at.
We can now write the method main() to use this method to create the destination file for the file
copy operation:
Search WWH ::




Custom Search