您的位置:首页 > 编程语言 > Java开发

Java-实现多线程下载

2016-06-08 09:11 531 查看
import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

public class DownLoad {
//使用多线程下载
/*
* 1.实现断点下载
* 2.加快下载速度
* */
//以QQ轻聊版为例
private static String path = "http://192.168.199.1:8080/QQLight.exe";
private static int threadCount = 3;//总线程数
public static void main(String[] args){

try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if(code == 200){
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file,"rw");
int fileSize = conn.getContentLength();//获得服务器上文件的大小
raf.setLength(fileSize);
raf.close();
System.out.println("空文件已创建");
int blockSize = fileSize % threadCount == 0 ? fileSize /3 :fileSize /3 + 1;//线程每一块负责下载的大小
for(int threadID = 0; threadID < threadCount; threadID++){
int startPos = threadID * blockSize;
RandomAccessFile rafile = new RandomAccessFile(file,"rw");
rafile.seek(startPos);//从文件的什么位置开始下载

new DownLoadFile( threadID, path,
rafile, blockSize, startPos).start();
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();


}

//获得文件名

private static String getFileName(String path) {
int index = path.lastIndexOf("/");
String filename = path.substring(index + 1);
return filename;
}
private static class DownLoadFile extends Thread{
private int threadID;//线程号
private String path;//文件路径
private RandomAccessFile rafile;//随机访问文件读写
private int blockSize;//每一块的大小
private int startPos;//开始位置

public DownLoadFile(int threadID,String path,
RandomAccessFile rafile,int blockSize,int startPos)
{
this.threadID = threadID;
this.path = path;
this.rafile = rafile;
this.blockSize = blockSize;
this.startPos = startPos;
}
public void run(){
try {

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Range范围:1000-  表示传输从1000个字节以后的所有内容
conn.setRequestProperty("range","bytes=" + startPos + "-");

int code = conn.getResponseCode();
if(code == 206){
System.out.println(threadID+"下载开始");
InputStream in = conn.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
int length = 0;
while(length < blockSize && ((len = in.read(buf)) > 0)){
rafile.write(buf,0,len);
length += len;
}
rafile.close();
in.close();

System.out.println(threadID + "下载结束!");
}
} catch (Exception e) {
System.out.println(threadID + "下载出错!");
e.printStackTrace();
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息