package net.loonggg.test;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/***
* 多线程下载
*
* @author loonggg
*
*/
public class MutilDownloader {
// 开启的线程的个数
public static final int THREAD_COUNT = 3;
public static void main(String[] args) throws Exception {
String path = "http://down.360safe.com/yunpan/360wangpan_setup.exe";
// 连接服务器,获取一个文件,获取文件的长度,在本地创建一个大小跟服务器文件大小一样的临时文件
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置网络请求超时时间
conn.setConnectTimeout(5000);
// 设置请求方式
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
// 服务器返回的数据的长度,实际就是文件的长度
int length = conn.getContentLength();
System.out.println("----文件总长度----" + length);
// 在客户端本地创建出来一个大小跟服务器端文件一样大小的临时文件
RandomAccessFile raf = new RandomAccessFile("yunpan.exe", "rwd");
// 指定创建的这个文件的长度
raf.setLength(length);
// 关闭raf
raf.close();
// 假设是3个线程去下载资源
// 平均每一个线程下载的文件的大小
int blockSize = length / THREAD_COUNT;
for (int threadId = 1; threadId <= thread_count;="" threadid++)="" {="" 计算每个线程下载的开始位置和结束位置="" int="" startindex="(threadId" -="" 1)="" *="" blocksize;="" endindex="threadId" blocksize="" 1;="" if="" (threadid="=" thread_count)="" }="" system.out.println("----threadid---"="" +="" threadid="" "--startindex--"="" "--endindex--"="" endindex);="" 开启每一个线程="" new="" downloadthread(path,="" threadid,="" startindex,="" endindex)="" .start();="" **="" 下载文件的子线程,每一个线程下载对应位置的文件="" @author="" loonggg="" public="" static="" downloadthread="" extends="" thread="" private="" threadid;="" startindex;="" endindex;="" string="" path;="" @param="" path="" 下载文件在服务器上的路径="" 线程id="" 线程下载的开始位置="" 线程下载的结束位置="" downloadthread(string="" path,="" this.path="path;" this.threadid="threadId;" this.startindex="startIndex;" this.endindex="endIndex;" @override="" void="" run()="" try="" url="" url(path);="" httpurlconnection="" conn="(HttpURLConnection)" .openconnection();="" conn.setrequestmethod("get");="" 重要:请求服务器下载部分的文件="" 指定文件的位置="" conn.setrequestproperty("range",="" "bytes=" + startIndex + " -"="" conn.setconnecttimeout(5000);="" 从服务器请求全部资源的状态码200="" ok="" 如果从服务器请求部分资源的状态码206="" code="conn.getResponseCode();" system.out.println("---code---"="" code);="" inputstream="" is="conn.getInputStream();//" 已经设置了请求的位置,返回的是当前位置对应的文件的输入流="" randomaccessfile="" raf="new" randomaccessfile("yunpan.exe",="" "rwd");="" 随机写文件的时候从哪个位置开始写="" raf.seek(startindex);="" 定位文件="" len="0;" byte[]="" buffer="new" byte[1024];="" while="" ((len="is.read(buffer))" !="-1)" raf.write(buffer,="" 0,="" len);="" is.close();="" raf.close();="" system.out.println("线程"="" ":下载完毕了!");="" catch="" (exception="" e)="" e.printstacktrace();="" }<="">
|