原理解析:利用RandomAccessFile在本地创建一个随机访问文件,文件大小和服务器要下载的文件大小相同。根据线程的数量(假设有三个线程),服务器的文件三等分,并把我们在本地创建的文件同样三等分,每个线程下载自己负责的部分,到相应的位置即可。
<强>示例图:强>
<强>示例演示强>
进口java.io.InputStream; 进口java.io.RandomAccessFile; 进口java.net.HttpURLConnection; 进口java.net.URL; 公开课MutilDownload { 私有静态字符串路径=" http://192.168.80.85:8080/test.doc”; 私有静态最终int threadCount=3; 公共静态void main (String [] args) { 尝试{ 网址URL=new URL(路径); HttpURLConnection康涅狄格州=(HttpURLConnection) url.openConnection (); conn.setRequestMethod(“获得”); conn.setConnectTimeout (5000); int responseCode=conn.getResponseCode (); 如果(responseCode==200) { int contentLength=conn.getContentLength (); system . out。println(“长度”+ contentLength); RandomAccessFile rafAccessFile=新RandomAccessFile(”测试。医生”、“rw”); rafAccessFile.setLength (contentLength); int blockSize=contentLength/threadCount; for (int i=0;我& lt;threadCount;我+ +){ int startIndex=我* blockSize;//每个现成下载的开始位置 int endIndex=(i + 1) * blockSize - 1;//每个线程的结束位置 如果(我==threadCount - 1) {//最后一个线程 endIndex=contentLength - 1; } 新DownloadThread (startIndex, endIndex) .start (); } } }捕捉(异常e) { } } 私有静态类DownloadThread延伸线{ 私人int startIndex; 私人int endIndex; 私人int threadId; 公共DownloadThread (int, int endIndex int startIndex threadId) { 这一点。startIndex=startIndex; 这一点。endIndex=endIndex; 这一点。threadId=threadId; } @Override 公共空间run () { 尝试{ 网址URL=new URL(路径); HttpURLConnection康涅狄格州=(HttpURLConnection) url.openConnection (); conn.setRequestMethod(“获得”); conn.setConnectTimeout (5000); conn.setRequestProperty(“范围”、“字节=" + startIndex +“-”+ endIndex);//固定写法,请求部分资源 int responseCode=conn.getResponseCode ();//206表示请求部分资源 如果(responseCode==206) { RandomAccessFile rafAccessFile=新RandomAccessFile(”测试。医生”、“rw”); rafAccessFile.seek (startIndex); InputStream是=conn.getInputStream (); int len=1; byte[]新字节缓冲区=[1024]; 在((len=is.read(缓冲)!=1){ rafAccessFile。写(缓冲区,0,len); } rafAccessFile.close (); system . out。println(“线程“+ threadId +”下载完成”); } }捕捉(异常e) { } } } } >之前以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
java多线程下载文件原理解析