日记二 断点续传
来源:互联网 发布:unity3d 麻将 编辑:程序博客网 时间:2024/05/18 00:24
import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class test {private static String path = "网址";private static int threadcount = 3;public static void main(String[] args) {try {//联网URL url = new URL(path);HttpURLConnection connection =(HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setReadTimeout(4000);int code = connection.getResponseCode();if(code==200){//获取下载文件长度int length = connection.getContentLength();//在本地创建一样大的文件RandomAccessFile file = new RandomAccessFile(getFileName(path), "rw");file.setLength(length);int blockSize = length/threadcount;//计算每一个线程要下载的数据范围for(int i = 0 ;i<threadcount;i++){int starIndex = i*blockSize;int endIndex = (i+1)*blockSize;if(i==threadcount-1){endIndex = length -1;}//创建多个线程new DThread(starIndex, endIndex, i).start();}}} catch (Exception e) {e.printStackTrace();}}private static class DThread extends Thread {private int startIndex;private int endIndex;private int threadID;public DThread(int startIndex, int endIndex, int threadID) {super();this.startIndex = startIndex;this.endIndex = endIndex;this.threadID = threadID;}public void run() {try {URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(4000);connection.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);if(connection.getResponseCode()==206){System.out.println("xc"+startIndex+"开始下载");InputStream inputstream = connection.getInputStream();int len = -1;byte[] buffer = new byte[1024];RandomAccessFile file = new RandomAccessFile(getFileName(path), "rw");//记得seek到startIndex位置写入数据file.seek(startIndex);while((len=inputstream.read(buffer))!=-1){file.write(buffer,0,len);}file.close();System.out.println("xc"+threadID+"完成");}} catch (IOException e) {e.printStackTrace();}}}//截取文件名private static String getFileName(String path2) {String[] result = path2.split("/");return result[result.length - 1];}}
阅读全文
0 0
- 日记二 断点续传
- 多线程断点续传(二)
- 日记二
- 多线程断点续传研究之二
- 多线程断点续传研究之二
- 多线程断点续传研究之二
- 多线程断点续传研究之二
- android 多线程断点续传下载 二
- android 多线程断点续传下载 二
- Android 多线程断点续传下载 二
- android 多线程断点续传下载 二
- 断点续传和多线程下载(二)
- Android 多线程断点续传下载 二
- Android之断点续传(二)
- android 多线程断点续传下载 二
- android 之断点续传详解三部曲之[二] → 断点续传下载
- GBA探索日记(二)
- 读核日记(二)
- Nginx负载均衡
- 在WIN8下进行LINUX虚拟机搭建
- Thrift 的C与golang语言实现以及相互调用方式
- hiho一下 第158周 非法二进制数
- python and 和 or的用法
- 日记二 断点续传
- UVa 11988 破损的键盘 链表 双向队列
- 伪类与伪元素
- 【组合数学】八(容斥原理)
- 如何安装mayavi(以python 3.5为例)
- 4G模块网络通信
- 2017-7-9
- 1797: [Ahoi2009]Mincut 最小割
- 指纹识别开源代码SourceAFIS使用入门