直接看源代码:
package test;
import java.io.BufferedInputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
public class FileDownloadTest {
private static final int THREAD_COUNT = 10;
private CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
private long completeLength = 0;
private long fileLength;
//进行下载的线程
class DownloadThread extends Thread {
private URL url;
private RandomAccessFile file;
private long from;
private long end;
/**
* @param url 下载的URL
* @param file 下载完成之后存储的文件
* @param from 当前线程对应文件的起始位置
* @param end 当前线程对应文件的结束位置
*/
DownloadThread(URL url, RandomAccessFile file, long from, long end) {
this.url = url;
this.file = file;
this.from = from;
this.end = end;
}
public void run() {
try {
long pos = from;
byte[] buf = new byte[1024];
HttpURLConnection cn = (HttpURLConnection) url.openConnection();
//因为有些网站根据它判断是否是盗链接
cn.setRequestProperty("Referer", "");
//设置请求的起始和结束位置。
cn.setRequestProperty("Range", "bytes=" + from + "-" + end);
//如果请求错误,重试。
if(cn.getResponseCode() != 200 && cn.getResponseCode() != 206){
System.out.println("Responce Code: " + cn.getResponseCode());
run();
return;
}
BufferedInputStream bis = new BufferedInputStream(cn.getInputStream());
int len;
while ((len = bis.read(buf)) > 0) {
synchronized (file) {
file.seek(pos);
file.write(buf, 0, len);
}
pos += len;
completeLength += len;
System.out.println(completeLength * 100 / fileLength + "%");
}
cn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
latch.countDown();
}
}
public void download(String address) throws Exception {
URL url = new URL(address);
URLConnection cn = url.openConnection();
cn.setRequestProperty("Referer", "");
fileLength = cn.getContentLength();
long packageLength = fileLength / THREAD_COUNT;
long leftLength = fileLength % THREAD_COUNT;
RandomAccessFile file = new RandomAccessFile("sapco.rar", "rw");
System.out.println(fileLength);
//计算每个线程请求的起始位置和结束位置。
long pos = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
long endPos = pos + packageLength;
if(leftLength > 0) {
endPos++;
leftLength--;
}
new DownloadThread(url, file, pos, endPos).start();
pos = endPos;
}
latch.await();
}
public static void main(String[] args) throws Exception {
long time = System.currentTimeMillis();
new FileDownloadTest()
.download("");
System.out.println(System.currentTimeMillis() - time);
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10742815/viewspace-611955/,如需转载,请注明出处,否则将追究法律责任。