首页 / JAVA / JAVA下实现多线程断点下载
JAVA下实现多线程断点下载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JAVA下实现多线程断点下载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含7555字,纯文字阅读大概需要11分钟。
内容图文
![JAVA下实现多线程断点下载](/upload/InfoBanner/zyjiaocheng/1235/4e6b47331bbe4f28a17fd445feb065a5.jpg)
多线程断点下载:顾名思义是用多线程实现的,断点是当第三方因素(断电、断网等)中断下载时,下次下载可以继续上次下载的地方下载。
1、通过getContentLength可以获取要下载文件的大小,这样可以在本机上创建一个相同大小的文件用来下载。
int fileLength = connection.getContentLength();
2、由于是多线程,所以要给每一个线程均分分配要下载的位置。
for(int i = 0; i < threadCount; i ++) { int startThread = i * blockSize; int endThread = (i + 1) * blockSize - 1; if( i == blockSize - 1) endThread = fileLength -1; new DownloadThread(i, startThread, endThread).start(); }
3、启动每个线程下载时,请求头需要Range参数,值是bytes:xxx-xxx某事。比如"Range:0-10100",代表要下载的位置是从0到10100。
connection.setRequestProperty("Range", "bytes:"+startThred+"-" + endThread);
4、然后每次用RandomAccessFile写入数据到本机文件里。
while((length = inputStream.read(buffer)) != -1) { randomAccessFile.write(buffer, 0, length); }
5、当然每次下载时需要记录本线程下载了多少,以便断点时,下载的时候可以从下次下载的地方下载。
total += length; int currentThreadPostion = startThred + total; RandomAccessFile randomAccessFile2 = new RandomAccessFile(file, "rwd"); randomAccessFile2.write(String.valueOf(currentThreadPostion).getBytes()); randomAccessFile2.close();
继承Thread类的DownloadThread类代码:
![技术分享](/img/jia.gif)
![技术分享](/img/jian.gif)
1 public static class DownloadThread extends Thread { 2privateint threadId; 3privateint endThread; 4privateint startThred; 5public DownloadThread(int threadId, int startThred, int endThread) { 6this.threadId = threadId; 7this.startThred = startThred; 8this.endThread = endThread; 9 } 10publicvoid run() { 11//分段请求网络连接,分段保存在本地12synchronized (DownloadThread.class) { 13 currentRunThreadCount += 1; 14 } 15try { 16 System.err.println("理论线程:"+threadId+",开始位置:"+startThred+",结束位置:"+endThread); 17 URL url = new URL(path); 18 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 19 connection.setRequestMethod("GET"); 20 connection.setConnectTimeout(10 * 1000); 21 File file = new File(threadId+".txt"); 22if(file.exists()) { //是否断点23 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); 24 String lastPostion_str = bufferedReader.readLine(); 25 startThred = Integer.parseInt(lastPostion_str); 26 bufferedReader.close(); 27 } 28//设置分段下载的头信息 Range:做分段29 connection.setRequestProperty("Range", "bytes:"+startThred+"-" + endThread); 30int code = connection.getResponseCode(); 31 System.out.println(code); 32if(code == 206) { //200:请求全部资源成功 206:代表部分资源请求成功33 InputStream inputStream = connection.getInputStream(); 34 System.out.println(getFileName(path)); 35 RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName(path)), "rw"); 36 randomAccessFile.seek(startThred); 37byte[] buffer = newbyte[1024*10]; 38int length = -1; 39int total = 0;//记录下载的总量40 System.err.println("实际线程:"+threadId+",开始位置:"+startThred+",结束位置:"+endThread); 41while((length = inputStream.read(buffer)) != -1) { 42 randomAccessFile.write(buffer, 0, length); 43 total += length; 44int currentThreadPostion = startThred + total; 45 RandomAccessFile randomAccessFile2 = new RandomAccessFile(file, "rwd"); 46 randomAccessFile2.write(String.valueOf(currentThreadPostion).getBytes()); 47 randomAccessFile2.close(); 48 } 49 randomAccessFile.close(); 50 inputStream.close(); 51 System.err.println("线程:"+threadId+"下载完毕"); 52synchronized (DownloadThread.class) { 53 currentRunThreadCount -= 1; 54if(currentRunThreadCount == 0){ 55for(int i = 0; i < threadCount; i ++) { 56 File file2 = new File(i+".txt"); 57 file2.delete(); 58 } 59 } 60 } 61 } 6263 } catch (Exception e) { 64 e.printStackTrace(); 65 } 666768super.run(); 69 } 70 }
完整代码:
![技术分享](/img/jia.gif)
![技术分享](/img/jian.gif)
1 package cn.starry.muchThreadDown; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.InputStream; 7 import java.io.InputStreamReader; 8 import java.io.RandomAccessFile; 9 import java.net.HttpURLConnection; 10 import java.net.MalformedURLException; 11 import java.net.URL; 12 import java.net.URLConnection; 13 14 import javax.swing.text.StyledEditorKit.BoldAction; 15 16 public class MuchThreadDown { 17 18 /** 19 * @param args 20 */ 21 private static int threadCount = 3; 22privatestaticint blockSize; 23privatestatic String path = "http://192.168.0.112:8080/itheima74/feiq.exe"; 24privatestaticint currentRunThreadCount = 0; 25publicstaticvoid main(String[] args) { 26 27try { 28 URL url = new URL(path); 29 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 30 connection.setRequestMethod("GET"); 31 connection.setConnectTimeout(10 * 1000); 32int code = connection.getResponseCode(); 33if(code == 200) { 34int fileLength = connection.getContentLength(); 35 RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName(path)), "rw"); 36 randomAccessFile.setLength(fileLength); 37 blockSize = fileLength / threadCount; 38for(int i = 0; i < threadCount; i ++) { 39int startThread = i * blockSize; 40int endThread = (i + 1) * blockSize - 1; 41if( i == blockSize - 1) endThread = fileLength -1; 42new DownloadThread(i, startThread, endThread).start(); 43 44 } 45 } 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 50 } 51 52 53publicstaticclass DownloadThread extends Thread { 54privateint threadId; 55privateint endThread; 56privateint startThred; 57public DownloadThread(int threadId, int startThred, int endThread) { 58this.threadId = threadId; 59this.startThred = startThred; 60this.endThread = endThread; 61 } 62publicvoid run() { 63synchronized (DownloadThread.class) { 64 currentRunThreadCount += 1; 65 } 66//分段请求网络连接,分段保存在本地 67try { 68 System.err.println("理论线程:"+threadId+",开始位置:"+startThred+",结束位置:"+endThread); 69 URL url = new URL(path); 70 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 71 connection.setRequestMethod("GET"); 72 connection.setConnectTimeout(10 * 1000); 73 File file = new File(threadId+".txt"); 74if(file.exists()) { //是否断点 75 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); 76 String lastPostion_str = bufferedReader.readLine(); 77 startThred = Integer.parseInt(lastPostion_str); 78 bufferedReader.close(); 79 } 80//设置分段下载的头信息 Range:做分段 81 connection.setRequestProperty("Range", "bytes:"+startThred+"-" + endThread); 82int code = connection.getResponseCode(); 83 System.out.println(code); 84if(code == 206) { //200:请求全部资源成功 206:代表部分资源请求成功 85 InputStream inputStream = connection.getInputStream(); 86 System.out.println(getFileName(path)); 87 RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName(path)), "rw"); 88 randomAccessFile.seek(startThred); 89byte[] buffer = newbyte[1024*10]; 90int length = -1; 91int total = 0;//记录下载的总量 92 System.err.println("实际线程:"+threadId+",开始位置:"+startThred+",结束位置:"+endThread); 93while((length = inputStream.read(buffer)) != -1) { 94 randomAccessFile.write(buffer, 0, length); 95 total += length; 96int currentThreadPostion = startThred + total; 97 RandomAccessFile randomAccessFile2 = new RandomAccessFile(file, "rwd"); 98 randomAccessFile2.write(String.valueOf(currentThreadPostion).getBytes()); 99 randomAccessFile2.close(); 100 } 101 randomAccessFile.close(); 102 inputStream.close(); 103 System.err.println("线程:"+threadId+"下载完毕"); 104synchronized (DownloadThread.class) { 105 currentRunThreadCount -= 1; 106if(currentRunThreadCount == 0){ 107for(int i = 0; i < threadCount; i ++) { 108 File file2 = new File(i+".txt"); 109 file2.delete(); 110 } 111 } 112 } 113 } 114115 } catch (Exception e) { 116 e.printStackTrace(); 117 } 118119120super.run(); 121 } 122 } 123124publicstatic String getFileName(String path) { 125return path.substring(path.lastIndexOf("/")+1); 126 } 127128 }
原文:http://www.cnblogs.com/xingkongyihao/p/7401771.html
内容总结
以上是互联网集市为您收集整理的JAVA下实现多线程断点下载全部内容,希望文章能够帮你解决JAVA下实现多线程断点下载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。