java多线程下载_java多线程批量下载文件

多线程下载文件

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

packagetest;

/**

*文件下载类

* @author luweicheng

*

*/

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();

}

/**

*初始化

*

* @throws IOException

*/

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();

}

}

}

/**

*下载线程类

*

* @author luweicheng

*

*/

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();

}

}

}

}

}

效果展示:

170ef61dcee5dd92d8f30b8cefb5b67d.png

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

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页