Java多线程下载文件实例详解
程序员文章站
2024-03-03 15:48:40
本文实例为大家分享了java多线程下载文件的具体代码,供大家参考,具体内容如下
import java.io.file;
import java.io.inp...
本文实例为大家分享了java多线程下载文件的具体代码,供大家参考,具体内容如下
import java.io.file; import java.io.inputstream; import java.io.randomaccessfile; import java.net.httpurlconnection; import java.net.url; public class multhreaddownload { public static void main(string[] args) throws exception { string path = "http://192.168.1.100:8080/hello/big.exe"; new multhreaddownload().download(path, 3); } /** * 下载文件 * * @param path * 网络文件路径 * @param threadsize * 线程数 * @throws exception */ private void download(string path, int threadsize) throws exception { url url = new url(path); httpurlconnection connection = (httpurlconnection) url.openconnection(); connection.setrequestmethod("get"); connection.setconnecttimeout(5000); if (connection.getresponsecode() == 200) { int length = connection.getcontentlength();// 获取网络文件长度 file file = new file(getfilename(path)); // 在本地生成一个长度与网络文件相同的文件 randomaccessfile accessfile = new randomaccessfile(file, "rwd"); accessfile.setlength(length); accessfile.close(); // 计算每条线程负责下载的数据量 int block = length % threadsize == 0 ? length / threadsize : length / threadsize + 1; for (int threadid = 0; threadid < threadsize; threadid++) { new downloadthread(threadid, block, url, file).start(); } } else { system.out.println("download fail"); } } private class downloadthread extends thread { private int threadid; private int block; private url url; private file file; public downloadthread(int threadid, int block, url url, file file) { this.threadid = threadid; this.block = block; this.url = url; this.file = file; } @override public void run() { int start = threadid * block; // 计算该线程从网络文件什么位置开始下载 int end = (threadid + 1) * block - 1; // 计算下载到网络文件什么位置结束 try { randomaccessfile accessfile = new randomaccessfile(file, "rwd"); accessfile.seek(start); //从start开始 httpurlconnection connection = (httpurlconnection) url .openconnection(); connection.setrequestmethod("get"); connection.setconnecttimeout(5000); //设置获取资源数据的范围,从start到end connection.setrequestproperty("range", "bytes=" + start + "-" + end); //注意多线程下载状态码是 206 不是200 if (connection.getresponsecode() == 206) { inputstream inputstream = connection.getinputstream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputstream.read(buffer)) != -1) { accessfile.write(buffer, 0, len); } accessfile.close(); inputstream.close(); } system.out.println("第" + (threadid + 1) + "条线程已经下载完成"); } catch (exception e) { e.printstacktrace(); } } } /** * 获取文件名称 * * @param path * 网络文件路径 * @return */ private string getfilename(string path) { return path.substring(path.lastindexof("/") + 1); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。