public class DownloadWithRange implements Runnable{
private String urlLocation;
private String filePath;
private long start;
private long end;
DownloadWithRange(String urlLocation, String filePath, long start, long end) {
this.urlLocation = urlLocation;
this.filePath = filePath;
this.start = start;
this.end = end;
}
@Override
public void run() {
try {
HttpURLConnection conn = getHttp();
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
File file = new File(filePath);
RandomAccessFile out = null;
if (file != null) {
out = new RandomAccessFile(file, "rw");
}
out.seek(start);
InputStream in = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) >= 0) {
out.write(b, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
e.getMessage();
}
}
public HttpURLConnection getHttp() throws IOException {
URL url = null;
if (urlLocation != null) {
url = new URL(urlLocation);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
return conn;
}
}
public class DownloadFileWithThreadPool {
//多线程下载一张图片,进行数据切分
public void getFileWithThreadPool(String urlLocation, String filePath, int poolLength) throws IOException {
//创建线程池
ExecutorService threadPool = Executors.newCachedThreadPool();
long len = getContentLength(urlLocation);
System.out.println(len);
//任务切分
for (int i = 0; i < poolLength; i++) {
long start = i * len / poolLength;
long end = (i + 1) * len / poolLength - 1;
if (i == poolLength - 1) {
end = len;
}
System.out.println(start+"---------------"+end);
DownloadWithRange download = new DownloadWithRange(urlLocation, filePath, start, end);
//多线程执行
threadPool.execute(download);
}
threadPool.shutdown();
}
//获取数据
public static long getContentLength(String urlLocation) throws IOException {
URL url = null;
if (urlLocation != null) {
url = new URL(urlLocation);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
long len = conn.getContentLength();
return len;
}
public static void main(String[] args) {
Date startDate = new Date();
DownloadFileWithThreadPool pool = new DownloadFileWithThreadPool();
try {
pool.getFileWithThreadPool("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3950359295,879559074&fm=11&gp=0.jpg", "D:\\tmp\\1.jpg", 100);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(new Date().getTime() - startDate.getTime());
}
}
使用多线程下载单个文件
最新推荐文章于 2022-09-24 10:46:56 发布