package com.zzw.download;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MultiThreadDownload {
private static int threadCount =3;
private static String path="http://192.168.1.102:8080/file.txt";
public static void main(String[] args) {
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
int code=connection.getResponseCode();
if (code==200) {
int length=connection.getContentLength();
File file=new File(getFileName(path));
RandomAccessFile raf=new RandomAccessFile(file, "rw");
raf.setLength(length);
raf.close();
int blockSize=length/threadCount;
for(int threadId=0;threadId<threadCount;threadId++){
int startIndex=threadId*blockSize;
int endIndex=(threadId+1)*blockSize-1;
if(threadId==(threadCount-1)){
endIndex=length-1;
}
new DownloadFilePartThread(threadId, startIndex, endIndex).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class DownloadFilePartThread extends Thread{
private int threadId;
private int startIndex;
private int endIndex;
public DownloadFilePartThread(int threadId, int startIndex,int endIndex) {
this.threadId=threadId;
this.startIndex=startIndex;
this.endIndex=endIndex;
}
@Override
public void run() {
System.out.println("第"+threadId+"线程开始下载了:下载 从"+startIndex+"~"+endIndex);
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setRequestProperty("range", "bytes="+startIndex+"-"+endIndex);
int code=connection.getResponseCode();
if(code==206){
InputStream in=connection.getInputStream();
File file=new File(getFileName(path));
RandomAccessFile raf=new RandomAccessFile(file, "rw");
raf.seek(startIndex);
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))>0){
raf.write(buf,0,len);
}
in.close();
raf.close();
}
System.out.println("第"+threadId+"线程下载结束了");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static String getFileName(String path){
int index=path.lastIndexOf("/");
return path.substring(index+1);
}
}