在实际的下载中会使用多线程下载,这样会抢占更多的CPU资源来增强下载速度:
public class MulThreadDownLoad(){
public static final void main(String[] args){
String path = "http://127.0.0.1:8080/myweb/test.text"
new MulThreadDownLoad().downLoad(path);
}
//下载文件方法
private downLoad(String path,int threadSize){
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.setLength(length);
accessFile.close();
//计算每条线程下载的数据量
int block = length%threadSize==0 ? length/threadSize: length/threadSize+1;
//开启多个线程
for(int threadId=0;threadId<threadSize;threadId++){
new DownloadThread().start();
}
}
}
private String getFileName(String path){
return path.subString(path.lastIndexOf("/"));
}
private class DownloadThread extend Thread{
private int threadId;
private int block;
private URL url;
private File file;
private DownloadThread (int threadId,int block,URL url,File file){
this.threadId=threadId;
...
}
public void run(){
int start= threadId*block;
int end = (threadId+1)*block-1;
RandomAccessFile accessFile = new RandomAccessFile(file,"rwd");
accessFile.seek(start);
HttpURLConnection conn=HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("range","bytes="+start+"-"+end);
//注意分段下载返回的成功码值为206,不是200
if(conn.getResponseCode()==206){
//省略流读取数据
InputStream in = conn.getInputStream();
}
}
}
}