多线程下载文件

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


public class Demo {


static int length;
private static int threadCount = 5;


public static void main(String[] args) throws Exception {
String path = "http://c.hiphotos.baidu.com/image/pic/item/dbb44aed2e738bd4713eca94a38b87d6277ff97c.jpg";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();


conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
length = conn.getContentLength();
// 创建一个和文件一样大小的文件
RandomAccessFile raf = new RandomAccessFile("test.jpg", "rwd");
raf.setLength(length);
raf.close();


// 假设是threadCount个线程
// 平均每一个线程下载的文件的大小
int block = length / threadCount;
for (int threadId = 1; threadId <= threadCount; threadId++) {


// 开始的位置,和结束的位置
int startIndex = (threadId - 1) * block;
int endIndex = threadId * block - 1;
// 当不能整除的时候,最后一个就是到末尾的位置
if (threadId == threadCount) {
endIndex = length;
}


System.out.println("线程" + threadId + "下载:------" + startIndex
+ "----->" + endIndex);


new DownloadThread(path, threadId, startIndex, endIndex)
.start();
}


} else {
System.out.println("服务器错误");
}


}


public static class DownloadThread extends Thread {
String path;
int threadId;
int startIndex;
int endIndex;


DownloadThread(String path, int threadId, int startIndex, int endIndex) {
this.path = path;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}


// 此线程下载文件的
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
// 请求支援的范围,后面是从哪一个位置开始
conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
+ endIndex);
int code = conn.getResponseCode();
InputStream is = conn.getInputStream();// 由于设置了位置,所以就是取部分类容,默认是下载全部内容
// 将多个文件写成一个,需要使用randomFillAccess
RandomAccessFile raf = new RandomAccessFile("test.jpg", "rwd");
raf.seek(startIndex);// 定位文件
int 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("线程的ID:" + threadId + "下载完毕了。。。");


} catch (Exception e) {
e.printStackTrace();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值