断点续传


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();
}
}





}



[img]http://dl.iteye.com/upload/attachment/613570/7efeb00b-8f02-3d13-8d95-db5f9cab6d16.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值