模拟断点下载文件
学了随机访问流 RandomAccessFile 可以操作文件指针,就想模拟一下断点下载.
将g:\模拟软件.rar
复制到g:\模拟软件copy.rar
利用一次复制任意一部分,下次继续从上次下载到的指针位置开始下载,不覆盖已经复制了一部分的源文件,继续拼接成完整的文件.
package com.westos.morning;
import java.io.*;
import java.util.Scanner;
public class Demo5 {
public static void main(String[] args) throws IOException {
String srcRount="g:\\模拟软件.rar";//源文件路径
String detRount="g:\\模拟软件copy.rar";//目的文件路径
File srcfile = new File(srcRount);//封装源文件
RandomAccessFile in = new RandomAccessFile(srcfile, "rw");
FileOutputStream out = new FileOutputStream(detRount, true);//复制后的文件路径
RandomAccessFile pointerFile = new RandomAccessFile("pointer.pro", "rw");//用于保存文件指针位置
Scanner scanner = new Scanner(System.in);
System.out.println("********************************************************************");
System.out.println("*描述:\n" +
"*一.按1后,如果输入的兆b大于源文件兆b数,将全部下载.\n" +
"*二.按1后,如果输入的兆b数小于源文件兆b,则断点下载.再运行按2即可接连断点全部下载\n" +
"*三.不按1直接按2,将全部下载." );
System.out.println("********************************************************************\n");
System.out.println("按1下载指定字节数,按2下载其余部分");
if (scanner.hasNextLine()) {
int num = Integer.parseInt(scanner.nextLine());
switch (num) {
case 1:
pointerFile.writeInt(num);//写入标记1
System.out.println("输入你先下载多少mb(整数):");
int mb = Integer.parseInt(scanner.nextLine());
long l = pauseDownload(in, out, mb);//拿到下载多少mb时候的指针位置
pointerFile.writeLong(l);//写入保存复制文件当前复制到的指针
pointerFile.seek(0);//置用于保存指针的pointer.txt文件指针到开头
break;
case 2:
if (pointerFile.length() == 0) {
//这是不按1下载前一部分,而是直接按2,下载后一半部分
//这时候就下载全部
continueDownload(in, out, 0);
pointerFile.writeInt(num);//写入标记2
pointerFile.writeLong(0);
pointerFile.seek(0);//置用于保存指针的pointer.txt文件指针到开头
break;
} else if (pointerFile.readInt() == 1) {
long p = pointerFile.readLong();//读出文件上次的指针
//System.out.println(p);
continueDownload(in, out, p);//从上次下载指针的下一位置继续下载
pointerFile.seek(0);//置用于保存指针的pointer.txt文件指针到开头
pointerFile.writeInt(num);//写入标记2
pointerFile.writeLong(0);
pointerFile.seek(0);//置用于保存指针的pointer.txt文件指针到开头
break;
} else {
System.out.println("你已经下载了");
break;
}
default:
System.out.println("输入错误");
break;
}
}
}
private static long pauseDownload(RandomAccessFile in, FileOutputStream out, int mb) throws IOException {
int len = 0;
byte[] bytes = new byte[1024];
while (in.getFilePointer() < mb * 1024 * 1024 && (len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
return in.getFilePointer();
}
private static void continueDownload(RandomAccessFile in, FileOutputStream out, long p) throws IOException {
int len = 0;
byte[] bytes = new byte[1024];
while ((len = in.read(bytes)) != -1) {
if (in.getFilePointer() > p)
out.write(bytes, 0, len);
out.flush();
}
}
}
结果:
谢谢!