浏览 1601 次
锁定老帖子 主题:断点续传
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-12-29
package com.log4e.union; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import org.junit.Test; public class Download { /** * * @param sURL 文件地址 * @param nPos 文件指针位置 * @param savePath 下载保存路径 * @throws IOException */ boolean stop = false; public void down(String sURL,long nPos,String savePath) throws IOException{ URL url = new URL(sURL); HttpURLConnection httpConnection = (HttpURLConnection) url .openConnection(); httpConnection.setConnectTimeout(5000000); httpConnection.setRequestProperty("User-Agent", "NetFox"); String sProperty = "bytes=" + nPos + "-"; // nStartPos 字节开始传,前面的字节不用传了 httpConnection.setRequestProperty("RANGE", sProperty); Utility.log(sProperty); InputStream input = httpConnection.getInputStream(); byte[] b = new byte[1024*10]; //"rw" 读写方式打开文件 RandomAccessFile oSaveFile = new RandomAccessFile(savePath, "rw"); //seek()方法来访问记录,并进行读写 oSaveFile.seek(nPos); int result = -1; System.out.println("下载中...."); while((result = input.read(b))!=-1){ oSaveFile.write(b, 0, result); } System.out.println("下载完成...."); httpConnection.disconnect(); } //获得文件长度 public long getFileSizeByUrl(String url) throws Exception{ URL u = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) u.openConnection(); long length = httpURLConnection.getContentLength(); httpURLConnection.disconnect(); return length; } // @Test public void testDownLoad(){ String url = "http://ww4.sinaimg.cn/bmiddle/769c42dcjw1dojdmycmu9g.gif"; String savePath = "F:\\download"; String fileName = url.substring(url.lastIndexOf("/")); File file = new File(savePath + fileName); try { long serverFileLength = getFileSizeByUrl(url); System.out.println("serverFileLength : "+serverFileLength ); if (file.exists()) { if(file.length()<serverFileLength){ down(url, file.length(), file.getPath()); } }else{ file.createNewFile(); if(file.length()<serverFileLength){ down(url, file.length(), file.getPath()); } } } catch (Exception e) { e.printStackTrace(); } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |