package com.dong.multhreaddownload;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class TestMain {
static int threadCont = 3;
/**
* @param args
* @throws MalformedURLException
*/
public static void main(String[] args) throws Exception {
// TOMCAT WEBAPP/ROOT中,存放一个EXE文件
String path ="http://192.168.1.100:8080/cbox2.4.0.9.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (200 == code) {
int length = conn.getContentLength();
System.out.println("file length is" + length);
//创建一个文件
RandomAccessFile raf = new RandomAccessFile("cbox2.4.0.9.exe", "rwd");
raf.setLength(length);
raf.close();
// 平均每一个线程的大小
int blockSize = length / threadCont;
for (int threadId = 1; threadId <= threadCont; threadId++) {
int startIndex = (threadId - 1) * blockSize;
int endIndex = threadId * blockSize - 1;
if (threadId == threadCont) {
endIndex = length;
}
System.out.println("Thread :" + threadId + "下载" + startIndex
+ "--->" + endIndex);
new DownThread(threadId, startIndex, endIndex, path).start();
}
} else {
System.out.println("server error");
}
}
public static class DownThread extends Thread {
private int ThreadId;
private int startIndex,endIndex;
private String path;
public DownThread(int threadId, int startIndex, int endIndex,String path) {
this.ThreadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.path = path;
}
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
conn.setRequestMethod("GET");
int code= conn.getResponseCode();//如果请求全部资源200代表OK,请求部分资源,206代表OK
System.out.println("code is "+code);
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("cbox2.4.0.9.exe", "rwd");
raf.seek(startIndex);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer))!=-1) {
raf.write(buffer,0,len);
}
System.out.println("thread"+ThreadId+ "is downed");
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
多线程下载基础示例JAVA SE
最新推荐文章于 2024-07-29 13:42:44 发布