您的位置:首页 > 编程语言 > Java开发

java实现多线程下载

2012-08-18 13:46 393 查看
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownLoad {

private String urlStr;

public DownLoad(String urlStr) {
this.urlStr = urlStr;
}

/**
* 获得下载的资源的名称
*
* @return 资源的名称
*/
private String getResourceName() {
return urlStr.substring(urlStr.lastIndexOf("/") + 1);

}

/**
* 开启四个线程进行下载
*/
public void doWork() {
System.out.println(getResourceName());
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();

if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

int size = conn.getContentLength();
System.out.println(size);
File file = new File("./" + getResourceName());

RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(size);
accessFile.close();

int block = (size % 4 == 0) ? (size / 4) : (size / 4 + 1);
System.out.println(block);
for (int i = 0; i < 4; i++) {
new DownLoadThread(url, file, block, i).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @param args
*/
public static void main(String[] args) {
DownLoad downLoad = new DownLoad(
"http://downmini.kugou.com/Kugou2012.exe");
downLoad.doWork();
}

}

/**
* 下载线程类
* @author zimei.zhang
*
*/
class DownLoadThread extends Thread {
private URL url; // url地址
private File file; // 下载文件
private int block; // 下载信息长度
private int threadPid; // 线程id

/**
* 构造函数
* @param url
* @param file
* @param block
* @param threadPid
*/
public DownLoadThread(URL url, File file, int block, int threadPid) {
this.url = url;
this.file = file;
this.block = block;
this.threadPid = threadPid;
}

/**
* 实现下载
*/
public void run() {
// 计算该线程要下载信息的范围
int startPosition = threadPid * block;
int endPosition = (threadPid + 1) * block - 1;

try {
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.seek(startPosition);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
conn.setRequestProperty("Range", "bytes=" + startPosition + "-"
+ endPosition);
InputStream in = conn.getInputStream();

byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
accessFile.write(buf, 0, len);
}
in.close();
accessFile.close();
System.out.println("Thread id: " + threadPid + " finished");
} catch (Exception e) {
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: