IO实战-RandomAccessFile在本地实现伪断点续传
生活随笔
收集整理的這篇文章主要介紹了
IO实战-RandomAccessFile在本地实现伪断点续传
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
準(zhǔn)備:在磁盤中 準(zhǔn)備一個(gè)目錄文件
實(shí)現(xiàn):將該文件復(fù)制到目標(biāo)路徑中,關(guān)掉程序,再重新打開可以在原位置繼續(xù)復(fù)制。
需求如下:
過程中顯示文件的拷貝的百分比
復(fù)制過程中關(guān)掉程序。
重新啟動(dòng)該程序時(shí),若上次沒有拷貝完,則提示上次拷貝還沒完成,是否從上次的位置開始拷貝! 1. 是:從上次結(jié)束的位置繼續(xù)拷貝。0 否:從頭開始拷貝
代碼如下:
public class Test02 {
public static void main(String[] args) {
File srcFile = new File("D:/test/test.zip");
File dstFile = new File("D:/test/test2.zip");
File logFile = new File(dstFile.getParentFile(),dstFile.getName() + ".log.raf");
RandomAccessFile logRaf = null;
long start = 0L;
try {
if(logFile.exists() && logFile.length() > 0){
Scanner sc = new Scanner(System.in);
System.out.println("上次拷貝結(jié)束:1 繼續(xù)拷貝 0重新拷貝");
switch (sc.nextInt()) {
case 1:
logRaf = new RandomAccessFile(logFile, "rw");
start = logRaf.readLong();
copy(srcFile,dstFile,start);
break;
case 0:
copy(srcFile,dstFile,start);
default:
System.out.println("輸入錯(cuò)誤,請(qǐng)輸入一個(gè) 0或1 的數(shù)字 進(jìn)行選擇");
break;
}
}else{
copy(srcFile,dstFile,start);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copy(File srcDir,File dstFile,long start){
long length = srcDir.length();
File logRaf = new File(dstFile.getParentFile(),dstFile.getName() + ".log.raf");
RandomAccessFile srcRandom = null;
RandomAccessFile dstRandom = null;
RandomAccessFile logRandom = null;
try {
if(length == 0){
return;
}
srcRandom = new RandomAccessFile(srcDir, "rw");
dstRandom = new RandomAccessFile(dstFile, "rw");
logRandom = new RandomAccessFile(logRaf, "rw");
long sum = start;
int read = -1;
int startavg = 0;
byte b[] = new byte[1024];
srcRandom.seek(start);
while((read = srcRandom.read(b)) != -1){
dstRandom.write(b,0,read);
sum += read;
int avg = (int)(100 * sum/length);
if(avg > startavg){
System.out.println("已經(jīng)完成了%:" + avg);
startavg = avg;
}
logRandom.seek(0);
logRandom.writeLong(sum);
Thread.currentThread().sleep(1);//降低寫的速度 效果明顯
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(logRandom != null){
try {
logRandom.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(dstRandom != null){
try {
dstRandom.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(srcRandom != null){
try {
srcRandom.close();
} catch (IOException e) {
e.printStackTrace();
}
}
logRaf.delete();
}
}
總結(jié)
以上是生活随笔為你收集整理的IO实战-RandomAccessFile在本地实现伪断点续传的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 踝关节韧带断裂怎么办
- 下一篇: 喜来登酒店品牌历史介绍