public class MultithreadingDown {
public static void main(String[] args) throws Exception {
// 链接资源
URL url = new URL("http://localhost:8080/20140808/up/a.txt");
// 获取服务器文件的大小
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setRequestMethod("GET");
con.setReadTimeout(3000);
con.connect();
int code = con.getResponseCode();
if (code == 200) {
// 获取大小
int size = con.getContentLength();
File dest = new File("F:\\scratch-file\\a01\\a.txt");
// 创建一个同等大小的文件
@SuppressWarnings("resource")
RandomAccessFile raf = new RandomAccessFile(dest, "rw");
raf.setLength(size);
// 计算每个线程应该下多少个字节
int threadCount = 3;
int sizePerThread = size / threadCount
+ (size % threadCount == 0 ? 0 : 1);
System.err.println("每个线程下载多少" + sizePerThread);
// 计算每个线程从哪里下载至少到什么地方
for (int i = 0; i
int start = i * sizePerThread;
int end = start + (sizePerThread - 1);
System.err.println(i + ":" + start + "~" + end);
new MyThread(url, dest, start, end).start();
}
}
}
static class MyThread extends Thread {
private URL url;
private File dest;
private int start;
private int end;
public MyThread(URL uu, File dd, int s, int e) {
this.url = uu;
this.dest = dd;
this.start = s;
this.end = e;
}
@Override
public void run() {
try {
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
con.setReadTimeout(3000);
con.setRequestMethod("GET");
con.setRequestProperty("range", "bytes=" + start + "-" + end);
con.setDoInput(true);
con.connect();
int code = con.getResponseCode();
if (code == 206) {
InputStream in = con.getInputStream();
byte[] b = new byte[1024];
int len = 0;
RandomAccessFile rand = new RandomAccessFile(dest, "rw");
rand.seek(start);
while ((len = in.read(b)) != -1) {
rand.write(b, 0, len);
}
rand.close();
}
System.err.println(this.getName()+"over");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}