Java Reference
In-Depth Information
AsynchronousCloseException is thrown if either channel is closed by another thread while the
operation is in progress.
ClosedByInterruptException is thrown if another thread interrupts the current thread while the
operation is in progress.
IOException is 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 you have seen.
A file copy program is an obvious candidate for trying out these methods.
TRY IT OUT: Direct Data Transfer between Channels
This example is a program that copies the file that is specified by a command-line argument. You copy
the file to a backup file that you create in the same directory as the original. You create the name of the
new file by appending "_backup" to the original filename as many times as necessary to form a unique
filename. That operation is a good candidate for writing a helper method:
// Method to create a unique backup Path object under MS Windows
public static Path createBackupFilePath(Path file) {
Path parent = file.getParent();
String name = file.getFileName().toString();
// 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 Path object that is a unique
Path backup = parent.resolve(
name.substring(0,period) + nameAdd +
name.substring(period));
while(Files.exists(backup)) {
// If the path already
exists...
name = backup.getFileName().toString(); // Get the current
file name
backup = parent.resolve(name.substring(0,period) +
// add
_backup
nameAdd + name.substring(period));
period += nameAdd.length();
// Increment separator
index
}
return backup;
Search WWH ::




Custom Search