Java-实现多线程下载

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();
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值