今天review代碼又看到某個“大神”使用古老的方法來實現文件的復制發火,今天歸結一下使用Java語言如何實現快速文件復制:
代碼1:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class Test {
public static void main(String[] args){
long start = System.currentTimeMillis();
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel inFileChannel = null;
FileChannel outFileChannel = null;
try {
fileInputStream = new FileInputStream(new File("C:\\from\\不是鬧著玩的.flv"));
fileOutputStream = new FileOutputStream(new File("C:\\to\\不是鬧著玩的.flv"));
inFileChannel = fileInputStream.getChannel();
outFileChannel = fileOutputStream.getChannel();
inFileChannel.transferTo(0, inFileChannel.size(), outFileChannel);//連接兩個通道,從in通道讀取數據寫入out通道。
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileInputStream != null){
fileInputStream.close();
}
if(inFileChannel != null){
inFileChannel.close();
}
if(fileOutputStream != null){
fileOutputStream.close();
}
if(outFileChannel != null){
outFileChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("視頻文件從“from”文件夾復制到“to”文件需要" + (end - start) + "毫秒。");
}
}
代碼運行結果為:
代碼2:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args){
long start = System.currentTimeMillis();
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try{
fileInputStream = new FileInputStream(new File("C:\\from\\不是鬧著玩的.flv")); //讀入原文件
fileOutputStream = new FileOutputStream("C:\\to\\不是鬧著玩的.flv");
byte[] bufferArray = new byte[1024*1024];
int length;
while ((length = fileInputStream.read(bufferArray)) != -1) {
fileOutputStream.write(bufferArray, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileInputStream != null){
fileInputStream.close();
}
if(fileOutputStream != null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("視頻文件從“from”文件夾復制到“to”文件需要" + (end - start) + "毫秒。");
}
}
代碼運行結果為:
代碼1和代碼2復制是同樣的文件,由此可見。
大話設計模式(帶目錄完整版) PDF+源代碼 http://www.linuxidc.com/Linux/2014-08/105152.htm
Java中介者設計模式 http://www.linuxidc.com/Linux/2014-07/104319.htm
Java 設計模式之模板方法開發中應用 http://www.linuxidc.com/Linux/2014-07/104318.htm
設計模式之 Java 中的單例模式(Singleton) http://www.linuxidc.com/Linux/2014-06/103542.htm