Java Reference
In-Depth Information
catch(IOException e) {
// Handle the exception
}
}
}
Copying Contents of a File
You can use buffers and channels to copy a file much faster. Copying the contents of a file to another file is just one
method call when you use a FileChannel . Get the FileChannel object for the source file and the destination file,
and call the transferTo() method on the source FileChannel object or call the transferFrom() method on the sink
FileChannel object. The following snippet of code shows how to copy file luci5.txt to luci5_copy.txt :
// Obtain the source and sink channels
FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
FileChannel sinkChannel = new FileOutputStream(sinkFile).getChannel();
// Copy source file contents to the sink file
sourceChannel.transferTo(0, sourceChannel.size(), sinkChannel);
// Instead of using the transferTo() method on the source channel,
// you can also use the transferFrom() method on the sink channel
sinkChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
Listing 9-9 contains the complete code. The program prints the path of the source and destination files when the
file copy succeeds.
Listing 9-9. Copying a File's Contents Using a FileChannel
// FastestFileCopy.java
package com.jdojo.nio;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class FastestFileCopy {
public static void main(String[] args) {
File sourceFile = new File("luci5.txt");
File sinkFile = new File("luci5_copy.txt");
try {
copy(sourceFile, sinkFile, false);
System.out.println(sourceFile.getAbsoluteFile() +
" has been copied to " +
sinkFile.getAbsolutePath());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
 
Search WWH ::




Custom Search