栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

java多线程下载

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java多线程下载

多线程下载文件

平时开发中有时会用到文件下载,为了提高文件的下载速率,采用多线程下载能够达到事半功倍的效果:

packagetest;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

public class DownFile{

private URLfileUrl;//文件下载路径

private intthreadCount;//文件下载的线程数

private intstartPos;//每个线程下载文件的开始位置

private intsize;//每个线程下载文件的长度

private intfileLength;//文件总程度

private StringpathName;//下载的文件路径(包含文件名)

private Downthread[] tDownthreads;//线程数组

public DownFile(URLurl,intthreadCount,StringpathName)throws IOException{

fileUrl=url;

this.threadCount=threadCount;

this.pathName=pathName;

init();

}

private void init()throws IOException{

tDownthreads= new Downthread[threadCount];

HttpURLConnectionconn=(HttpURLConnection) fileUrl.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

conn.setRequestProperty("connection","keep-alive");

fileLength=conn.getContentLength();

System.out.println("文件长度" +fileLength);

size=fileLength/threadCount;

System.out.println("每个下载量==" +size);

conn.disconnect();//断开链接

}

public URL getFileUrl() {

returnfileUrl;

}

public int getThreadCount() {

return this.threadCount;

}

public void startDown() {

for(inti= 0; i

try{

RandomAccessFileraFile= new RandomAccessFile(pathName,"rw");

tDownthreads[i]= new Downthread(i*size, raFile, i);

tDownthreads[i].start();

}catch(FileNotFoundExceptione) {

e.printStackTrace();

}

}

}

class Downthread extends Thread{

private intstartPos;//开始的位置

private InputStreamis;

private RandomAccessFileraFile;

private intlength;//下载的文件长度

private intflag;//线程标志

public Downthread(intstartPos,RandomAccessFileraFile,inti) {

this.startPos=startPos;

this.raFile=raFile;

flag=i;

}

@Override

public void run() {

try{

HttpURLConnectionconnection=(HttpURLConnection) fileUrl.openConnection();

connection.setRequestMethod("GET");

connection.setRequestProperty("connection","keep-alive");

connection.setConnectTimeout(5 * 1000);

is=connection.getInputStream();

is.skip(startPos);

raFile.seek(startPos);

byte[] buf= new byte[8 * 1024];

inthasread= 0;//读出的字节数

//将位置在 startPos - startPos 位置的数据读出写入

while(length

raFile.write(buf,0, hasread);

length+=hasread;

System.out.println("*****线程" +flag+ "下载了*********" +length);

}

System.out.println("*******线程" +flag+ "下载完成*********");

}catch(IOExceptione) {

}finally{

try{

is.close();

raFile.close();

}catch(IOExceptione) {

e.printStackTrace();

}

}

}

}

}

效果展示:

​

详细配置信息可以参考这篇文章:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1023463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号