使用流
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
使用通道
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
使用Apache下議院IO LIB:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
使用Java SE 7文件類:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
性能測試:
File source = new File("/Users/pankaj/tmp/source.avi");
File dest = new File("/Users/pankaj/tmp/dest.avi");
//copy file conventional way using Stream
long start = System.nanoTime();
copyFileUsingStream(source, dest);
System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
//copy files using java.nio FileChannel
source = new File("/Users/pankaj/tmp/sourceChannel.avi");
dest = new File("/Users/pankaj/tmp/destChannel.avi");
start = System.nanoTime();
copyFileUsingChannel(source, dest);
System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
//copy files using apache commons io
source = new File("/Users/pankaj/tmp/sourceApache.avi");
dest = new File("/Users/pankaj/tmp/destApache.avi");
start = System.nanoTime();
copyFileUsingApacheCommonsIO(source, dest);
System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
//using Java 7 Files class
source = new File("/Users/pankaj/tmp/sourceJava7.avi");
dest = new File("/Users/pankaj/tmp/destJava7.avi");
start = System.nanoTime();
copyFileUsingJava7Files(source, dest);
System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));
結果:
/*
* File copy:
* Time taken by Stream Copy = 44582575000
* Time taken by Channel Copy = 104138195000
* Time taken by Apache Commons IO Copy = 108396714000
* Time taken by Java7 Files Copy = 89061578000
*/
鏈接:
http://www.journaldev.com/861/4-ways-to-copy-file-in-java
開始[基本I/O](http://docs.oracle.com/javase/tutorial/essential/io/),也嘗試在看看[複製文件或目錄](http://docs.oracle.com/javase/tutorial/essential/io/copy.html) – MadProgrammer 2013-05-08 06:20:38
我的第一個問題是如何存儲該搜索文件? – vijayk 2013-05-08 06:23:18
我不確定爲什麼你需要,但是,看看[Collections](http://docs.oracle.com/javase/tutorial/collections/TOC.html),我會專注於'List ' – MadProgrammer 2013-05-08 06:25:29