public class Multidownloader {
private static int ThreadCount = 3;
public static void main(String[] args) throws Exception {
String path = "http://192.168.0.100/Server/e.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code == 200) {
int length = conn.getContentLength();
RandomAccessFile raf = new RandomAccessFile("temp.exe", "rwd");
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 DownLoaderThread(threadId, startIndex, endIndex).start();
}
}
}
public static class DownLoaderThread extends Thread {
private int threadId;
private int startIndex;
private int endIndex;
public DownLoaderThread(int threadId,int startIndex,int endIndex) {
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@Override
public void run() {
try {
System.out.println("线程" + threadId + "起始索引:" + startIndex);
System.out.println("线程" + threadId + "结束索引:" + endIndex);
String path = "http://192.168.0.100/Server/e.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
int code = conn.getResponseCode();
if(code == 206) {
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe", "rwd");
raf.seek(startIndex);
int len = 0;
byte[] bys = new byte[1024];
while((len = is.read(bys)) != -1) {
raf.write(bys,0,len);
}
raf.close();
is.close();
System.out.println("线程" + threadId + "下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}