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();
}
}
}
}
多线程下载
最新推荐文章于 2024-09-13 15:47:50 发布