import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoader {
public static void main(String[] args) throws Throwable {
new DownLoader().download();
}
public void download() throws Throwable {
String fileName = "F:/qq.exe";
String path = "http://dldir1.qq.com/qqfile/qq/QQ8.3/18038/QQ8.3.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int fileLength = conn.getContentLength();// 文件大小长度
System.out.println("fileLength = " + fileLength);
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.setLength(fileLength);
file.close();
conn.disconnect();
int threadSize = 3;// 5个线程
int threadLength = fileLength % threadSize == 0 ? fileLength
/ threadSize : fileLength / threadSize + 1;
System.out.println("每条线程下载的长度threadLength = " + threadLength);
for (int i = 0; i < threadSize; i++) {
int startPosition = i * threadLength;
RandomAccessFile threadFile = new RandomAccessFile(fileName, "rw");
threadFile.seek(startPosition);
new DownLoadThread(i, path, startPosition, threadFile, threadLength).start();
}
}
private class DownLoadThread extends Thread {
int threadId;
int startPosition;
RandomAccessFile threadFile;
int threadLength;
String path;
public DownLoadThread(int threadId, String path, int startPosition,
RandomAccessFile threadFile, int threadLength) {
this.threadId = threadId;
this.path = path;
this.startPosition = startPosition;
this.threadFile = threadFile;
this.threadLength = threadLength;
}
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes = " + startPosition
+ "-");// 指定从文件的什么位置开始下载
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
int length = 0;
while (length < threadLength
&& (len = inputStream.read(buffer)) != -1) {
threadFile.write(buffer, 0, len);
length += len;
System.out.println((threadId + 1) + "下载进度 = " + length);
}
threadFile.close();
inputStream.close();
System.out.println("线程" + (threadId + 1) + "已经下载完成");
} catch (Exception e) {
e.printStackTrace();
System.out.println("线程" + (threadId + 1) + "已经下载出错" + e);
}
}
}
}