import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoadWithMulThread {
private final int ThreadNum=3;
public static void main(String[] args) {
try{
new DownLoadWithMulThread().DoDownload("http://ftp.yz.yamagata-u.ac.jp/pub/eclipse//oomph/epp/neon/R1/eclipse-inst-win64.exe");
}catch(Exception ex){
}
}
private void DoDownload(String path) throws Exception{
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
int length=conn.getContentLength();
String fileName=GetFileNameByPath(path);
File sfile=new File(fileName);
//在本地生成一个和网络文件大小相等的文件
RandomAccessFile rfile=new RandomAccessFile(sfile, "rwd");
rfile.setLength(length);
rfile.close();
int block=length % ThreadNum==0?length/ThreadNum:length/ThreadNum+1;
for(int i=0;i<ThreadNum;i++){
new MulThread(i,block,sfile,path).start();
}
}
else{
System.out.println("下载失败");
}
}
private String GetFileNameByPath(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
private class MulThread extends Thread{
private int threadIndex;
private int block;
private File sfile;
private String path;
public MulThread(int i, int block, File sfile, String path) {
this.threadIndex=i;
this.block=block;
this.sfile=sfile;
this.path=path;
}
@Override
public void run() {
int start=threadIndex*block;
int end=(threadIndex+1)*block-1;
try {
RandomAccessFile rfile=new RandomAccessFile(sfile,"rwd");
rfile.seek(start);
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
//按区间请求文件的字节数
conn.setRequestProperty("Range", "bytes="+start+"-"+end);
if(conn.getResponseCode()==206){
InputStream instream=conn.getInputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=instream.read(buffer))>-1){
rfile.write(buffer,0,len);
}
instream.close();
rfile.close();
System.out.println("线程"+threadIndex+"下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
//super.run();
}
}
}
java多线程下载 备忘
最新推荐文章于 2023-12-10 08:00:00 发布