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