Java使用FileChannel进行文件拷贝
FileChannel属于nio,FileChannel底层会利用操作系统的零拷贝进行优化,效率较io高。
导包
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
1.当所拷贝的文件小于2G时
代码
public void channelCopy(String sourcePath,String destPath){
try {
FileChannel sourceChannel = new FileInputStream(sourcePath).getChannel();
FileChannel destChannel = new FileOutputStream(destPath).getChannel();
sourceChannel.transferTo(0,sourceChannel.size(),destChannel);
} catch (IOException e) {
e.printStackTrace();
}
}
说明
sourcePath:源地址,如E:\xx\yy\a.txt
destPath:目的地址,如D:\yy\a.txt
sourceChannel.transferTo(0,sourceChannel.size(),destChannel);
参数说明
0:表示从源文件的什么位置开始拷贝。
sourceChannel.size():拷贝多大。
destChannel:拷贝到那里去。
该方法的返回值为真实拷贝的size。该方法最大拷贝2G,超出2G的部分将丢弃。
解决掉异常,以及流关闭的完整封装
public void channelCopy(String sourcePath,String destPath){
FileChannel sourceChannel=null;
FileChannel destChannel=null;
try {
sourceChannel = new FileInputStream(sourcePath).getChannel();
destChannel = new FileOutputStream(destPath).getChannel();
sourceChannel.transferTo(0,sourceChannel.size(),destChannel);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (sourceChannel!=null){
sourceChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (destChannel!=null){
destChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.所拷贝内容大于2G
//超过 2g 大小的文件传输
public void channelCopy(String sourcePath,String destPath){
try {
FileChannel sourceChannel = new FileInputStream(sourcePath).getChannel();
FileChannel destChannel = new FileOutputStream(destPath).getChannel();
//所要拷贝的原文件大小
long size=sourceChannel.size();
for (long left=size;left>0;){
//transferSize所拷贝过去的真实长度
//size - left计算出下次要拷贝的位置
long transferSize = sourceChannel.transferTo((size - left), left, destChannel);
//还剩余多少
left=left-transferSize;
}
} catch (IOException e) {
e.printStackTrace();
}
}
解决掉异常,以及流关闭的完整封装
//超过 2g 大小的文件传输
public void channelCopy(String sourcePath,String destPath){
FileChannel sourceChannel=null;
FileChannel destChannel=null;
try {
sourceChannel = new FileInputStream(sourcePath).getChannel();
destChannel = new FileOutputStream(destPath).getChannel();
long size=sourceChannel.size();
for (long left=size;left>0;){
long transferSize = sourceChannel.transferTo((size - left), left, destChannel);
left=left-transferSize;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (sourceChannel!=null){
sourceChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (destChannel!=null){
destChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}