用Java实现断点续传的基本思路和代码

用Java实现断点续传的基本思路和代码

URL url = new URL(http://www.oschina.net/no-exist.zip);

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

//设置User-Agent
httpConnection.setRequestProperty("User-Agent","NetFox");
//设置断点续传的开始位置
httpConnection.setRequestProperty("RANGE","bytes=2000070");
//获得输入流
InputStream input = httpConnection.getInputStream();
/**
从输入流中取出的字节流就是no-exist.zip文件从2000070开始的字节流。
大家看,其实断点续传用Java实现起来还是很简单的吧。
接下来要做的事就是怎么保存获得的流到文件中去了。
(2)保存文件采用的方法
我采用的是IO包中的RandAccessFile类。操作相当简单,假设从2000070处开始保存文件,代码如下:
 
*/
 
RandomAccessFile oSavedFile = new RandomAccessFile("down.zip","rw");
 
long nPos = 2000070;
 
//定位文件指针到nPos位置
 
oSavedFile.seek(nPos);
 
byte[] b = new byte[1024];
 
int nRead;
 
//从输入流中读入字节流,然后写到文件中
 
while((nRead=input.read(b,0,1024)) > 0)
 
{
 
oSavedFile.write(b,0,nRead);
 
}

 

转自:http://www.oschina.net/code/snippet_54100_623

posted on 2016-03-30 09:50  Leoxlu  阅读(424)  评论(0编辑  收藏  举报

导航