日期:2014-05-20  浏览次数:20635 次

大家帮我看看这段从网络多线程下载的程序吧,
package com.junjun.download;

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

public class MulThreadDownload {

public static void main(String[] args) throws Exception{
String path = "http://192.168.1.101:8080/videonews/thinkpython.pdf";
new MulThreadDownload().download(path,3);
}
/**
 * 下载文件
 * @param path 文件路径
 */
private void download(String path,int threadsize)throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
int length = conn.getContentLength();//获得网络文件的长度
File file = new File(getFilename(path));
RandomAccessFile accessFile = new RandomAccessFile(file,"rwd");//在本地生成与网络文件长度相等的文件accessFile
accessFile.setLength(length);
accessFile.close();
//计算每条线程负责下载的数据量
int block = length%threadsize==0 ? length/threadsize : length/threadsize + 1;
for(int threadid = 0 ; threadid<threadsize ; threadid++){
new DownloadThread(threadid,block,url,file).start();
}
}else{
System.out.println("访问失败!");
}

}
private class DownloadThread extends Thread{
private int threadid;
private int block;
private URL url;
private File file;
public DownloadThread(int threadid, int block, URL url, File file) {
this.block = block;
this.file = file;
this.threadid = threadid;
this.url = url;
}
@Override
public void run() {
int start = threadid*block;//计算出该线程从网络文件下载的开始位置
int end = (threadid+1)*block -1;//计算出该线程从网络文件下载的结束位置;
try {
RandomAccessFile accessFile = new RandomAccessFile(file,"rwd");//在本地生成与网络文件长度相等的文件accessFile
accessFile.seek(start);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes =" + start + "-" + end);
//if(conn.getResponseCode()==206){
System.out.println(conn.getResponseCode());