现在的位置: 首页 > 综合 > 正文

断点续传

2013年12月04日 ⁄ 综合 ⁄ 共 650字 ⁄ 字号 评论关闭

以http下载为例

1.建立连接  

String urlStr = "下载地址url"

URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection)url.openConnection();

2.设置连接属性

String sProperty = "bytes=" + [int]开始下载的字节处(bytes) + "-"; 
con.setRequestProperty("RANGE", sProperty);

3.随机写入

File file = new File("下载路径+下载文件名");

RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");

randomAccessFile.seek(int[上一次下载的字节处])

InputSream is = con.getInputStream();

if(206 == con.getResponseCode()){//206是http断点续传返回的正常结果码,不再是200

//读入

byte[] buffer = new byte[1024];

int len = 0;

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

randomAccessFile.write(buf, 0, len);

//下载进度等等

}

}

randomAccessFile.close();
con.disconnect();

至于开子线程下载,保存上次下载的字节大小等就不列出了,上面写的连伪代码都算不上呵呵

抱歉!评论已关闭.