package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import org.apache.commons.io.FileUtils;public classtest {public static voidmain(String[] args) throws Exception{
File source=new File("D:\\MyLearningNotes\\test.txt");
File dest1=new File("D:\\MyLearningNotes\\test1.txt");
File dest2=new File("D:\\MyLearningNotes\\test2.txt");
File dest3=new File("D:\\MyLearningNotes\\test3.txt");
File dest4=new File("D:\\MyLearningNotes\\test4.txt");
copyFileUsingFileStreams( source, dest1);
copyFileUsingFileChannels(source, dest2);
copyFileUsingJava7Files(source, dest3);
copyFileUsingApacheCommonsIO(source, dest4);
}//1.Java流和File类
private static voidcopyFileUsingFileStreams(File source, File dest)
throws IOException {
InputStream input= null;
OutputStream output= null;try{
input= newFileInputStream(source);
output= newFileOutputStream(dest);byte[] buf = new byte[1024];intbytesRead;while ((bytesRead = input.read(buf)) > 0) {
output.write(buf,0, bytesRead);
}
}finally{
input.close();
output.close();
}
}//2.java.nio.channels.FileChannel类
private static voidcopyFileUsingFileChannels(File source, File dest) throws IOException {
FileChannel inputChannel= null;
FileChannel outputChannel= null;try{
inputChannel= newFileInputStream(source).getChannel();
outputChannel= newFileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel,0, inputChannel.size());
}finally{
inputChannel.close();
outputChannel.close();
}
}//3.Java7 java.nio.file.Files类
private static voidcopyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}//4.org.apache.commons.io.FileUtils类
private static voidcopyFileUsingApacheCommonsIO(File source, File dest)
throws IOException {
FileUtils.copyFile(source, dest);
}
}