您的位置:首页 > 理论基础 > 计算机网络

Java之多线程下载网络资源

2013-08-14 17:54 399 查看
package com.download;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader {

public void download() throws IOException
{
String fileName = "YNote.exe";
String path = "http://download.ydstatic.com/notewebsite/downloads/YNote.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int fileLength = conn.getContentLength();

RandomAccessFile file = new RandomAccessFile(fileName,"rw");
file.setLength(fileLength);
file.close();
conn.disconnect();

int threadNum = 10;  //线程数
//每条线程下载的长度
int threadLength = fileLength % threadNum == 0 ?
fileLength/threadNum : fileLength/threadNum + 1;

for(int i=0;i<threadNum;i++)
{
int startPosition = i * threadLength;
//开始写入文件的位置
RandomAccessFile threadFile = new RandomAccessFile(fileName,"rw");
threadFile.seek(startPosition);
new DownloadThread(i, path, startPosition, threadFile, threadLength).start();
}

}

class DownloadThread extends Thread
{
private int id;
private int startPosition;
private RandomAccessFile file;
private int threadLength;
private String path;

public DownloadThread(int i,String p,int s,RandomAccessFile f,int l)
{
id = i;
path = p;
startPosition = s;
file = f;
threadLength = l;
}

@Override
public void run() {
super.run();
try{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes="+startPosition+"-");
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024*10];
int len = -1;
int length = 0;
while(length<threadLength &&
(len=is.read(buffer))!=-1)
{
file.write(buffer,0,len);
length += len;
System.out.println("Thread"+(id+1)+" 已经下载"+length+"/"+threadLength);
}
file.close();
is.close();
System.out.println("Thread"+(id+1)+" 已经下载完成");
}catch(Exception e){
e.printStackTrace();
System.out.println("Thread"+(id+1)+" 下载失败");
}
}
}
}


本文出自 “白马坡居士” 博客,请务必保留此出处http://lauwai.blog.51cto.com/7444153/1272991
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: