Java实现断点下载Demo

本文介绍了一种基于HTTP协议的断点续传方法,通过设置请求头中的Range字段来实现文件的部分下载,适用于网络不稳定时的大文件下载场景。
 1 //1、声明URL
 2         String path="http://localhost:8080/day22_DownLoad/file/a.rmvb";
 3         URL url=new URL(path);
 4         //2、设置已下载文件
 5         String savePath="d:\\a.rmvb";
 6         File file=new File(savePath);
 7         long size=file.length();//文件当前大小,刚开始时返回0
 8         System.out.println(size);
 9         //3、设置连接
10         HttpURLConnection conn=  (HttpURLConnection) url.openConnection();
11         //4、设置访问类型
12         conn.setRequestMethod("GET");
13         //5、设置下载区间
14         conn.setRequestProperty("range","bytes="+size+"-");
15         conn.connect();
16         //6、状态码
17         int code=conn.getResponseCode();//断点是206
18         if(code==206)
19         {
20             InputStream in=conn.getInputStream();
21             int serviceSize=conn.getContentLength();
22             //必须使用
23             RandomAccessFile out=new RandomAccessFile(file, "rw");
24             //从size字节开始写
25             out.seek(size);
26             byte[] b=new byte[1024];
27             int len=-1;
28             while((len=in.read(b))!=-1)
29             {
30                 out.write(b,0,len);
31             }
32             out.close();
33         }

 

转载于:https://www.cnblogs.com/liuwt365/p/4158230.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值