多线程下载


package cn.com.hs.down;

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

/**
* 多线程下载文件
*
* @author Administrator
*
*/
public class DownFile {

public static void main(String[] args) {
DownFile test = new DownFile();
String path = "http://www.qthdaily.com/news/content/attachement/jpg/site1/20100622/0022687bd36c0d8a4cb206.jpg";
int threadnum = 3;
try {
test.down(path, threadnum);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 下载
*
* @throws Exception
*
*/
public void down(String path, int threadnum) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10 * 1000);
conn.setRequestMethod("GET");
// 获得网络文件的长度
int length = conn.getContentLength();
//每个线程负责下载的文件大小
int block = (length % threadnum) == 0 ? length / threadnum : length/ threadnum + 1;

/**
* 创建随进访问文件对象
* r:read w:write d:disk--将读取的数据存储到硬盘中,否则就存入到缓存中
*/
File file = new File(getFileName(path));
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(length);//设置长度;
accessFile.close();
if (conn.getResponseCode() == 200) {
for (int i = 0; i < threadnum; i++) {
// 开启线程下载
new DownThread(i, file, block, url).start();
}
}
}

public String getFileName(String path){
return path.substring(path.lastIndexOf("/")+1);
}

/**
* 下载线程
*
* @author Administrator
*
*/
public class DownThread extends Thread {

private int id; // 线程id

private File file;// 目标文件

private int block;// 每个线程下载文件的大小

private URL url;

public DownThread() {
}

public DownThread(int id, File file, int block, URL url) {
this.id = id;
this.file = file;
this.block = block;
this.url = url;
}

@Override
public void run() {
int start = (id * block);// 当前线程开始下载处
int end = (id + 1) * block - 1;// 当前线程结束下载处
// 建立随机操作文件对象
try {
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.seek(start);// 设置操作文件的入点
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
// 指定网络位置从什么位置开始下载,到什么位置结束
conn.setRequestProperty("Range", "bytes=" + start + "-" + end
+ "");
InputStream in = conn.getInputStream();// 获得输入流
byte[] data = new byte[1024];
int len = 0;
while ((len = in.read(data)) != -1) {
accessFile.write(data, 0, len);
}
accessFile.close();
in.close();
System.out.println("线程:" + id + "下载完成!");
} catch (Exception e) {
e.printStackTrace();
}
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值