package com.softeem.randomio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ContinueCopy {
public void copy1(File file, File dir) throws Exception {
RandomAccessFile raf_read = null;
RandomAccessFile raf_write = null;
long position = 0;
try {
position = readPosition(dir);
File target = new File(dir, file.getName());
raf_read = new RandomAccessFile(file, "r");
raf_write = new RandomAccessFile(target, "rw");
// raf_write.seek(position);
byte[] b = new byte[1024];
int len = 0;
int count = 0;
System.out.println("准备拷贝");
while ((len = raf_read.read(b)) != -1) {
count++;
position += len;//文件指针未知改变
System.out.println("---》"+count);
if (count == 8000) { //注意这个自定义异常,是用来测试文件下载中断的。
System.out.println(" 异常中断");
throw new IOException();
}
raf_write.write(b, 0, len);
}
new File(dir,"len.txt").delete();
} catch (IOException e) {
writePosition(position, dir);//记录文件中断时下载的位置
e.printStackTrace();
} finally {
try {
if (raf_read != null)
raf_read.close();
if (raf_write != null)
raf_write.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writePosition(long position, File dir) {//写文件的位置
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File(dir,"len.txt"), "rw");
raf.writeLong(position);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (raf != null)
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public long readPosition(File dir) {//读文件的位置
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File(dir, "len.txt"), "r");
raf.seek(0);
return raf.readLong();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null)
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return 0L;
}
public static void main(String[] args) throws Exception {
File f1 = new File("C:\\larva搞笑虫子\\2.mp4");
File f2 = new File("C:\\目的");
new ContinueCopy().copy1(f1, f2);
}
}
文件断点下载
最新推荐文章于 2024-06-21 09:18:06 发布