java多线程下载网络资源(支持断点续传)

时间:2022-11-26 11:06:46

package threadpic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ThreadDownPic {
static int threadCount = 4;
static int progressThread = 0;

static String path = "http://dlsw.baidu.com/sw-search-sp/soft/3a/12350/QQ_8.1.17255.0_setup.1456298445.exe";
public static void main(String[] args) {

URL url;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置一个指定的超时值(以毫秒为单位)
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
// 返回值从 HTTP 响应消息获取状态码。例如,就以下状态行来说:
// HTTP/1.0 200 OK
// HTTP/1.0 401 Unauthorized
if (conn.getResponseCode() == 200) {
System.out.println("联网成功!");
// 获取文件的长度
int length = conn.getContentLength();
File file = new File(getFileName());
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
// 设置文件的长度跟网络上获取的长度一致
raf.setLength(length);
raf.close();
int avg = length / threadCount;// 13/3=4...1
for (int i = 0; i < threadCount; i++) {
int start = avg * i;
int end = avg * (i + 1) - 1;
if (i == threadCount - 1) {
end = length - 1;
}
System.out.println("线程下载的区间" + start + "---" + end);
new DownThread(i, start, end).start();
}
} else {
System.out.println("联网失败!");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getFileName(){
return "D:\\"+path.substring(path.lastIndexOf("/")+1);
}

}

class DownThread extends Thread {

int threadId;
int startIndex;
int endIndex;

public DownThread(int threadId, int startIndex, int endIndex) {
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}

@Override
public void run() {
try {
// 创建临时文件进行存储下载的位置
File file = new File("D:\\"+threadId + ".txt");
int progressTotal = 0;
if (!file.exists()) {
file.createNewFile();
}else{
Reader r = new FileReader(file);
BufferedReader br = new BufferedReader(r);
//读取临时文件中存储的长度
progressTotal = Integer.parseInt(br.readLine());
startIndex+=progressTotal;
br.close();
}

URL url = new URL(ThreadDownPic.path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
// 设置请求数据的区间 Property性质
conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
+ endIndex);
// 请求部分数据成功
if (conn.getResponseCode() == 206) {
InputStream is = conn.getInputStream();
byte[] buff = new byte[1024 * 8];
// 设置读取到的位置
int index = 0;
int total = progressTotal;
RandomAccessFile raf = new RandomAccessFile(
ThreadDownPic.getFileName(), "rwd");
raf.seek(startIndex);
while ((index = is.read(buff)) != -1) {
raf.write(buff, 0, index);
total += index;
System.out.println(Thread.currentThread().getName() + "下载了"
+ total + "字节");
// 向临时文件中写入读取的字节数
RandomAccessFile rafProgress = new RandomAccessFile(file,
"rwd");
rafProgress.write((total + "").getBytes());
rafProgress.close();
}
System.out
.println(Thread.currentThread().getName() + "下载完成!!!");
ThreadDownPic.progressThread++;
synchronized (ThreadDownPic.path) {
if (ThreadDownPic.progressThread == ThreadDownPic.threadCount) {
for (int i = 0; i < ThreadDownPic.threadCount; i++) {
File progressFile = new File("D:\\"+threadId + ".txt");
// 删除临时文件
progressFile.delete();
ThreadDownPic.progressThread = 0;
}
}
}
raf.close();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}