HttpDownload

14 篇文章 0 订阅
package org.sl.bean;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * HTTP断点续传下载文件
 * @author ShanL
 *
 */
public class HttpDownload {
	private URL remoteFile = null;
	private File storeFile = null;
	
	/**
	 * 
	 * @param remoteFile
	 * @param storeFile
	 */
	public HttpDownload(URL remoteFile, File storeFile){
		this.remoteFile = remoteFile;
		this.storeFile = storeFile;
	}
	
	/**
	 * 执行下载
	 * @param rfPosit 远程文件开始下载位置
	 */
	public void start( long rfPosit){
		HttpURLConnection httpConn = null;
		InputStream httpIn = null;
		
		try{
			System.out.println("打开HttpURLConnection.");			
			httpConn = (HttpURLConnection)remoteFile.openConnection();
			httpConn.setRequestProperty("User-Agent","NetFox"); 
			httpConn.setRequestProperty("RANGE","bytes="+rfPosit+"-");
			
			System.out.println("得到HttpInputStream.");
			httpIn = httpConn.getInputStream();
			writeFile(httpIn);
			
			System.out.println("关闭HttpURLConnection.");
			httpConn.disconnect();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**
	 * 从HttpInputStream中读数据并写到本地文件中
	 * @param in HttpInputStream
	 */
	private void writeFile(InputStream in){
		RandomAccessFile fileOut = null;
		int buffer_len = 512;
		byte[] buffer = new byte[buffer_len];
		int readLen = 0;
		
		try{
			System.out.println("写本地文件.");
			
			fileOut = new RandomAccessFile(this.storeFile, "rw");
			fileOut.seek(fileOut.length());
			
			while(-1 != (readLen = in.read(buffer, 0, buffer_len))){
				fileOut.write(buffer, 0, readLen);
			}	
			
			fileOut.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
}


测试类:

package org.sl.test1;

import java.io.File;
import java.net.URL;

import org.sl.bean.HttpDownload;

public class HttpDownTest1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(true) t1();
	}

	static void t1(){	
		URL remoteFile = null;
		File storeFile = null;
		HttpDownload httpDown = null;
		
		try{
			remoteFile = new URL("http://192.168.1.113:8080/web_test1/test1.dat");
			storeFile = new File("d:\\test\\down.dat");
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		httpDown = new HttpDownload(remoteFile, storeFile);
		httpDown.start(23);
	}
}


参考文章:http://blog.csdn.net/jl19861101/article/details/5612022

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值