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

Java SE 多线程下载网络上的文件代码+注释

2015-04-08 10:43 134 查看
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.Test;

public class DownLoader {
@Test
public void download() throws Throwable{
String filename = "baiduTool.exe";
String path ="http://dlsw.baidu.com/sw-search-sp/soft/e2/28619/BaiduExpert_Setup_2.0.201.1910.1422515416.exe";
URL url = new URL(path);
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
int filelength = conn.getContentLength();//文件的长度
System.out.println(filelength);

RandomAccessFile file = new RandomAccessFile(filename, "rw");//得到随机文件类,第一个参数为文件名称,第二个参数是对文件的操作,rw是读写操作

file.setLength(filelength);//设置本地文件的长度,等于本地文件的长度
file.close();//关闭这个文件
conn.disconnect();//先断掉这个链接,这个方法不调用也可以的

int threadsize = 3;//设置要下载的线程数
int threadlength = filelength %3 == 0?filelength/3:filelength/3+1;//每条线程下载的长度
for(int i= 0;i<threadsize;i++){
int startposition = i* threadlength;//计算每条线程应该从文件的什么位置开始下载
RandomAccessFile threadfile = new RandomAccessFile(filename, "rw");
threadfile.seek(startposition);//从文件的什么位置开始写入数据
new DownLoadThread(i,path,startposition,threadfile,threadlength).start();
}
int quit =System.in.read();
while('q' != quit){
Thread.sleep(2*1000);
}
}

private class DownLoadThread extends Thread{
private int threadid;
private int startpositon;
private RandomAccessFile threadFile;
private int threadlength;
private String path;
public DownLoadThread(int threadid,String path,int startposition,RandomAccessFile threadFile,int threadlength){
this.threadid = threadid;
this.path= path;
this.startpositon= startposition;
this.threadFile = threadFile;
this.threadlength =threadlength;

}

@Override
public void run(){
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range","bytes="+startpositon+"-");//从指定文件从什么位置开始下载

InputStream inStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len =-1;
int length =0;//指的是当前线程下载的值,之后将下载的长度和每个线程下载的长度进行比较,如果小于就继续下载,如果大于就停止下循环
while(length<threadlength &&(len = inStream.read(buffer))!=-1){
threadFile.write(buffer,0,len);
length +=len;//累计下载长度
//当复制到第二条线程的时候,已经制定了开始写位置,写到自己的长度就应该断掉
}
threadFile.close();
inStream.close();
System.out.println("线程"+(threadid+1)+"已经下载完成");
} catch (Exception e) {
System.out.println("线程"+(threadid+1)+"下载出错了"+e);

}
}

}

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