- URL url = new URL("<a href="http://www.CodeSnippet.cn/no-exist.zip">http://www.CodeSnippet.cn/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.codesnippet.cn/detail/040120131269.html
来源: http://www.codesnippet.cn/detail/040120131269.html