JAVA 多线程下载
单线程下载
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;}@Overridepublic 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);}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
