FileChannel屬于nio,F(xiàn)ileChannel底層會(huì)利用操作系統(tǒng)的零拷貝進(jìn)行優(yōu)化,效率較io高。
導(dǎo)包
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
1.當(dāng)所拷貝的文件小于2G時(shí)代碼
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();
}
}
說(shuō)明
sourcePath:源地址,如E:\xx\yy\a.txt
destPath:目的地址,如D:\yy\a.txt
sourceChannel.transferTo(0,sourceChannel.size(),destChannel);
參數(shù)說(shuō)明
0:表示從源文件的什么位置開(kāi)始拷貝。
sourceChannel.size():拷貝多大。
destChannel:拷貝到那里去。
該方法的返回值為真實(shí)拷貝的size。該方法大拷貝2G,超出2G的部分將丟棄。
解決掉異常,以及流關(guān)閉的完整封裝
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.所拷貝內(nèi)容大于2G//超過(guò) 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所拷貝過(guò)去的真實(shí)長(zhǎng)度
//size - left計(jì)算出下次要拷貝的位置
long transferSize = sourceChannel.transferTo((size - left), left, destChannel);
//還剩余多少
left=left-transferSize;
}
} catch (IOException e) {e.printStackTrace();
}
}
解決掉異常,以及流關(guān)閉的完整封裝
//超過(guò) 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();
}
}
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧