多线程下载文件
平时开发中有时会用到文件下载,为了提高文件的下载速率,采用多线程下载能够达到事半功倍的效果:
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();
}
}
}
}
}
效果展示:
详细配置信息可以参考这篇文章:



