单线程下载
package com.autumn.lesson04;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @Author: autumn
* @Date: 2021/11/3
*/
public class FileDownload implements Runnable{
//下载路径
private String urlLocation;
//下载完存放路径
private String filePath;
//文件开始地址
private long start;
//文件结束地址
private long end;
public FileDownload(String urlLocation, String filePath, long start, long end) {
this.urlLocation = urlLocation;
this.filePath = filePath;
this.start = start;
this.end = end;
}
@Override
public void run() {
InputStream is = null;
RandomAccessFile out = null;
try {
//获取下载的部分
URL url = new URL(urlLocation);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
File file = new File(filePath);
out = null;
if (file != null) {
out = new RandomAccessFile(file, "rw");
}
out.seek(start);
is = conn.getInputStream();
byte[] bytes = new byte[1024];
int l = 0;
while ((l = is.read(bytes))!=-1){
out.write(bytes,0,l);
}
System.out.println(Thread.currentThread().getName()+"完成下载!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
实现多线程下载
package com.autumn.lesson04;
import java.net.URL;
import java.net.URLConnection;
/**
* @Author: autumn
* @Date: 2021/11/3
*/
public class Controller {
public void getFileWithThreadPool(String urlLocation, String filePath, int poolLength) throws Exception{
long start = 0;
int length = 0;
URL url = null;
url = new URL(urlLocation);
URLConnection urlConnection = url.openConnection();
//文件长度
length = urlConnection.getContentLength();
System.out.println(length);
for (int i = 0; i < poolLength; i++) {
start = i * length / poolLength;
long end = (i + 1) * length / poolLength - 1;
System.out.println(start+"---------------"+end);
Thread thread = new Thread(new FileDownload(urlLocation, filePath, start, end));
thread.setName("线程"+(i+1));
thread.start();
}
}
}
测试
package com.autumn.lesson04;
/**
* @Author: autumn
* @Date: 2021/11/3
*/
public class Test {
public static void main(String[] args) throws Exception{
Controller controller = new Controller();
controller.getFileWithThreadPool("https://issuecdn.baidupcs.com/issue/netdisk/yunguanjia/BaiduNetdisk_7.8.5.1.exe","D:\\autumn\\Desktop\\aaa\\百度.exe",5);
}
}