//这个是任务Bean
public class Task {
private String downURL;
private String saveFile;
private int bufferSize = 64 * 1024;
private int workerCount;
private int sectionCount;
private long contentLength;
private long[] sectionsOffset;
public static final int HEAD_SIZE = 4096;
//读下载描述文件内容
public synchronized void read(RandomAccessFile file) throws IOException {
byte[] temp = new byte[HEAD_SIZE];
file.seek(0);
int readed = file.read(temp);
if (readed != temp.length) {
throw new RuntimeException();
}
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
DataInputStream dis = new DataInputStream(bais);
downURL = dis.readUTF();
saveFile = dis.readUTF();
sectionCount = dis.readInt();
contentLength = dis.readLong();
sectionsOffset = new long[sectionCount];
for (int i = 0; i < sectionCount; i++) {
sectionsOffset[i] = file.readLong();
}
}
//创建下载描述文件内容
public synchronized void create(RandomAccessFile file) throws IOException {
if (sectionCount != sectionsOffset.length) {
throw new RuntimeException();
}
long len = HEAD_SIZE + 8 * sectionCount;
file.setLength(len);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(downURL);
dos.writeUTF(saveFile);
dos.writeInt(sectionCount);
dos.writeLong(contentLength);
byte[] src = baos.toByteArray();
byte[] temp = new byte[HEAD_SIZE];
System.arraycopy(src, 0, temp, 0, src.length);
file.seek(0);
file.write(temp);
writeOffset(file);
}
//更新下载的过程
public synchronized void writeOffset(RandomAccessFile file) throws IOException {
if (sectionCount != sectionsOffset.length) {
throw new RuntimeException();
}
file.seek(HEAD_SIZE);
for (int i = 0; i < sectionsOffset.length; i++) {
file.writeLong(sectionsOffset[i]);
}
}
(下面是Getter、Setter)
}
//这个是下载主程序
public class TaskAssign {
public void work(Task task) throws IOException {
File file = new File(task.getSaveFile());
if (file.exists()) {
return;
}
//这个是记录是否下载成功。我这里也没有增加失败回复、重试之类的工作。
final AtomicBoolean success = new AtomicBoolean(true);
//任务描述文件
File taskFile = new File(task.getSaveFile() + ".r_task");
//真正下载的文件
File saveFile = new File(task.getSaveFile() + ".r_save");
boolean taskFileExist = taskFile.exists();
RandomAccessFile taskRandomFile = null;
RandomAccessFile downRandomFile = null;
try {
taskRandomFile = new RandomAccessFile(taskFile, "rw");
downRandomFile = new RandomAccessFile(saveFile, "rw");
long rtnLen = getContentLength(task.getDownURL());
if (!taskFileExist) {
//如果文件不存在,就初始化任务文件和下载文件
task.setContentLength(rtnLen);
initTaskFile(taskRandomFile, task);
downRandomFile.setLength(rtnLen);
} else {
//任务文件存在就读取任务文件
task.read(taskRandomFile);
if (task.getContentLength() != rtnLen) {
throw new RuntimeException();
}
}
int secCount = task.getSectionCount();
//分配线程去下载,这里用到线程池
ExecutorService es = Executors.newFixedThreadPool(task.getWorkerCount());
for (int i = 0; i < secCount; i++) {
final int j = i;
final Task t = task;
final RandomAccessFile f1 = taskRandomFile;
final RandomAccessFile f2 = downRandomFile;
es.execute(new Runnable() {
public void run() {
try {
down(f1, f2, t, j);
} catch (IOException e) {
success.set(false);
e.printStackTrace(System.out);
}
}
});
}
es.shutdown();
try {
es.awaitTermination(24 * 3600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
taskRandomFile.close();
taskRandomFile = null;
downRandomFile.close();
downRandomFile = null;
//如果下载成功,去掉任务描述文件、帮下载文件改名
if (success.get()) {
taskFile.delete();
saveFile.renameTo(file);
}
} finally {
if (taskRandomFile != null) {
taskRandomFile.close();
taskRandomFile = null;
}
if (downRandomFile != null) {
downRandomFile.close();
downRandomFile = null;
}
}
}
public void down(RandomAccessFile taskRandomFile, RandomAccessFile downRandomFile, Task task, int sectionNo) throws IOException {
//这里我用HttpURLConnection下载,你也可以用HttpClient或者自己实现一个Http协议(不过貌似没有必要)
URL u = new URL(task.getDownURL());
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
long start = task.getSectionsOffset()[sectionNo];
long end = -1;
//这里要注意一下,这里是计算当前块的长度
if (sectionNo < task.getSectionCount() - 1) {
long per = task.getContentLength() / task.getSectionCount();
end = per * (sectionNo + 1);
} else {
end = task.getContentLength();
}
if (start >= end) {
System.out.println("Section has finished before. " + sectionNo);
return;
}
String range = "bytes=" + start + "-" + (end - 1);
conn.setRequestProperty("Range", range);
conn.setRequestProperty("User-Agent", "Ray-Downer");
try {
conn.connect();
if (conn.getResponseCode() != 206) {
throw new RuntimeException();
}
if (conn.getContentLength() != (end - start)) {
throw new RuntimeException();
}
InputStream is = conn.getInputStream();
byte[] temp = new byte[task.getBufferSize()];
BufferedInputStream bis = new BufferedInputStream(is, temp.length);
int readed = 0;
while ((readed = bis.read(temp)) > 0) {
long offset = task.getSectionsOffset()[sectionNo];
synchronized (task) {
//下载之后顺便更新描述文件,你可能会发现这里效率比较低,在一个线程同步里进行两次文件操作。你可以自己实现一个缓冲写。
downRandomFile.seek(offset);
downRandomFile.write(temp, 0, readed);
offset += readed;
task.getSectionsOffset()[sectionNo] = offset;
task.writeOffset(taskRandomFile);
}
}
} finally {
conn.disconnect();
}
System.out.println("Section finished. " + sectionNo);
}
public void initTaskFile(RandomAccessFile taskRandomFile, Task task) throws IOException {
int secCount = task.getSectionCount();
long per = task.getContentLength() / secCount;
long[] sectionsOffset = new long[secCount];
for (int i = 0; i < secCount; i++) {
sectionsOffset[i] = per * i;
}
task.setSectionsOffset(sectionsOffset);
task.create(taskRandomFile);
}
public long getContentLength(String url) throws IOException {
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
try {
return conn.getContentLength();
} finally {
conn.disconnect();
}
}
}
//稍微测试一下。
public class Main {
public static void main(String[] args) throws IOException {
test3();
System.out.println("\n\n===============\nFinished.");
}
public static void test1() throws IOException {
Task task = new Task();
task.setDownURL("http://61.152.235.21/qqfile/qq/2007iistable/QQ2007IIKB1.exe");
task.setSaveFile("H:/Test2.exe");
task.setSectionCount(200);
task.setWorkerCount(100);
task.setBufferSize(256 * 1024);
TaskAssign ta = new TaskAssign();
ta.work(task);
}
public static void test2() throws IOException {
Task task = new Task();
task.setDownURL("http://student1.scut.edu.cn:8880/manage/news/data/1208421861893.xls");
task.setSaveFile("H:/Test3.xls");
task.setSectionCount(5);
task.setWorkerCount(1);
task.setBufferSize(128 * 1024);
TaskAssign ta = new TaskAssign();
ta.work(task);
}
public static void test3() throws IOException {
Task task = new Task();
task.setDownURL("http://go.microsoft.com/fwlink/?linkid=57034");
task.setSaveFile("H:/vc2005express.iso");
task.setSectionCount(500);
task.setWorkerCount(200);
task.setBufferSize(128 * 1024);
TaskAssign ta = new TaskAssign();
ta.work(task);
}
public static void test4() throws IOException {
Task task = new Task();
task.setDownURL("http://down.sandai.net/Thunder5.7.9.472.exe");
task.setSaveFile("H:/Thunder.exe");
task.setSectionCount(30);
task.setWorkerCount(30);
task.setBufferSize(128 * 1024);
TaskAssign ta = new TaskAssign();
ta.work(task);
}
}
分享到:
相关推荐
这是我java的课程设计。本程序实现类似迅雷的多线程断点续传下载功能,并且有简单的界面,可以显示下载中各个线程的下载状况。 用Eclipse编译一下就能运行了。希望和大家共同学习!
该程序实现了java的多线程下载,显示下载进度条
Java多线程断点下载
下载,支持多线程,支持断点续传 下载记录在数据库中 如果在android手机中可以存储在SQLite数据库里
自己为了课程设计写的程序,基于java的多线程断点续传程序
本程序模拟了多线程的断点下载,简单易懂,通过该demo了解断点下载的机制。
多线程多任务可断点下载程序
可以使用Java中的多线程技术,例如通过创建多个线程同时下载文件的不同部分,从而提高下载速度和效率。 断点续传设计:为了支持断点续传,需要在下载过程中记录已下载的文件部分,并在下次下载时从断点处继续下载。...
资源名:2022年JAVA毕业设计精品项目源码29期:基于JAVA的多线程与线程安全的Http协议断点续传.zip 资源类型:毕业设计项目源码+论文 源码说明: 全部项目源码都是经过测试校正后百分百成功运行的,如果您下载后不能...
2、支持多任务多线程同时下载; 3、每个任务的线程数由用户在新建任务时自定义,缺省为5个线程; 4、任务下载过程中可以点击“线程+”或“线程-”即时增减线程; 5、选择任务,可以在任务信息栏中查看任务下载的信息...
多线程下载的程序,代码完整,可运行,帮助java的学习者更好的掌握断点续传的要点
Java多线程与线程安全实践-基于Http协议的断点续传.rarJava多线程与线程安全实践-基于Http协议的断点续传.rarJava多线程与线程安全实践-基于Http协议的断点续传.rarJava多线程与线程安全实践-基于Http协议的断点续传...
多线程-断点续传下载工具 功能描述: 实现同时下载多个文件,下载的过程中可以临时终止下载,可以随时继续下载。 该源码全是干货。核心源码一幕了然。
下载工具我想没有几个人不会用的吧,前段时间比较无聊,花了点时间用java写了个简单的http多线程下载程序,我实现的这个http下载工具功能很简单,就是一个多线程以及一个断点恢复,当然下载是必不可少的,需要的朋友...
计算机毕业设计 Java多线程与线程安全实践-基于Http协议的断点续传 代码论文 范文 模板 资源 JAVA程序源码
2、支持多任务多线程同时下载; 3、线程数由用户在新建任务时设定(若大于线程数20则默认为20); 4、下载过程中可以暂停,点击开始可以继续下载; 5、点击菜单栏“任务——退出程序”正常退出,可以保存当前未...
javaweb毕业设计-Java多线程与线程安全实践-基于Http协议的断点续传(可做课程设计).rarjavaweb毕业设计-Java多线程与线程安全实践-基于Http协议的断点续传(可做课程设计).rarjavaweb毕业设计-Java多线程与线程安全...
代码作用:多线程分段下载,加快下载速度,加入适当代码可支持断点下载 ================================================= ·示例代码位置: [项目目录]/src-app/app/DownloaderApp.java 代码里写了注释,有一定...
Java程序通常包括一个或多个类,每个类都包含了属性和方法。Java程序的入口点是一个特殊的类,它包含了一个名为main的方法,这个方法是程序的起点。Java程序可以使用各种开发工具进行编写、编译和调试,比如IntelliJ...