java 断点下载_java的断点下载

public static final int threadCount =3;

public static void main(String[] args) throws IOException {

String path = "http://localhost:8080/oppo.mp4";//下载文件的路径,也可以是网上的路径

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");//Get请求

int code = conn.getResponseCode();

if(code == 200){

int length = conn.getContentLength();//文件的大小

RandomAccessFile raf = new RandomAccessFile("setup.mp4", "rwd");

/**

"r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。

"rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。

"rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。

"rwd"   打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。

*/

raf.setLength(length);//指定创建这个文件的大小

raf.close();//关闭流

//假设是三个线程

int blockSize = length / threadCount;

for(int i = 1; i<=threadCount; i++){

int startIndex = (i-1)*blockSize;

int endIndex = i*blockSize-1;

if(i==threadCount){//当线程为最后一个线程,则末尾等于文件的大小

endIndex = length;

}

new DownloadThread(i, startIndex, endIndex, path).start();//开启线程

}

}

}

public static class DownloadThread extends Thread{

private int threadId;//线程的Id

private int startIndex;//下载的开始位置

private int endIndex;//下载的结束位置

private String path;//下载文件的路径

public DownloadThread(int threadId, int startIndex, int endIndex,

String path) {

super();

this.threadId = threadId;

this.startIndex = startIndex;

this.endIndex = endIndex;

this.path = path;

}

@Override

public void run() {

try {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);

int code = conn.getResponseCode();

System.out.println("code:"+code);

//从服务器请求全部的资源成功返回 200  如果从服务器请求部分资源成功返回 206

if(code == 206){

InputStream is = conn.getInputStream();//已经设置了setRequestProperty

//RandomAccessFile随机文件访问类,可以指定从某个位置开始下载

RandomAccessFile raf = new RandomAccessFile("setup.mp4", "rwd");

raf.seek(startIndex);//定位文件

int len = 0;

byte[] buffer = new byte[1024];

while((len = is.read(buffer)) != -1){

raf.write(buffer,0,len);

}

is.close();

raf.close();

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值