使用Java语言如何实现快速文件复制
发布网友
发布时间:2022-04-29 13:38
我来回答
共1个回答
热心网友
时间:2022-06-29 01:46
使用Java语言如何实现快速文件复制:
代码:
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) + "毫秒。");
}
}