多线程下载使用到的是随机文件访问类
代码如下:
package com.huawei;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @author zhangzhao E-mail: zz198808@sina.com
* @version 创建时间:2012-4-15 下午03:00:04
* 类说明
*/
public class MulThreadDown {
public static void main(String[] args) throws IOException {
String path="http://59.69.105.217:8080/web/QQ2011.exe";
new MulThreadDown().downLoad(path,3);
}
public void downLoad(String path,int threadNum) throws IOException{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setReadTimeout(5000);
if(con.getResponseCode()==200)
{
int length=con.getContentLength();
int block=length%threadNum==0?length/threadNum:length/threadNum+1;
File file=new File(getFileName(path));
RandomAccessFile randomAccessFile=new RandomAccessFile(file, "rwd");
randomAccessFile.setLength(length);
randomAccessFile.close();
for(int threadID=0;threadID<threadNum;threadID++){
new DownLoadThread(threadID,block,url,file).start();
}
}
}
private final 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.threadID=threadID;
this.block=block;
this.url=url;
this.file=file;
}
@Override
public void run() {
int startPos=threadID*block;
int endPos=(threadID+1)*block-1;
try {
RandomAccessFile randomAccessFile=new RandomAccessFile(file, "rwd");
randomAccessFile.seek(startPos);
HttpURLConnection con =(HttpURLConnection)url.openConnection();
con.setReadTimeout(5000);
con.setRequestMethod("GET");
con.setRequestProperty("Range", "bytes="+startPos+"-"+endPos);
//if(con.getResponseCode()==206)//分段的时候请求码不是200,是206
//{
System.out.println(con.getResponseCode());
InputStream inputStream=con.getInputStream();
int len=0;
byte[] buffer=new byte[4*1024];
while((len=inputStream.read(buffer))!=-1)
{
randomAccessFile.write(buffer, 0, len);
}
inputStream.close();
randomAccessFile.close();
System.out.println("第"+(threadID+1)+"条线程下载完成");
//}
} catch (Exception e) {
// TODO: handle exception
}
}
}
public String getFileName(String path)
{
int pos=path.lastIndexOf("/");
return path.substring(pos+1);
}
}