工具原理就是如果发现要下载的保存目录下文件已经存在,获取文件大小,然后下载时设置HttpURLConnection的Range值为文件大小,就从这个大小的地方开始继续下载,保存到文件时使用RandomAccessFile设置seek,添加保存到文件中,而不是覆盖原文件。
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadUtil {
private static final String ACCEPT = "Accept";
private static final String USER_AGENT = "User-Agent";
private static final String RANGE = "Range";
// private static final String COOKIE = "Cookie";
private static String accept = "*/*";
private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36";
/**
* 创建目录
* @param outPath
* @return
*/
public static File mkFile(String outPath) {
File file = new File(outPath);
if(file.isDirectory()){
if(!file.exists()){
file.mkdirs();
}
}else{
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
}
return file;
}
/**
* 获取HttpURLConnection
* @param urlPath
* @return
* @throws IOException
*/
private static HttpURLConnection getConnection(String urlPath) throws IOException {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(300000);
conn.setReadTimeout(300000);
conn.setRequestProperty(ACCEPT, accept);
conn.setRequestProperty(USER_AGENT, userAgent);
return conn;
}
/**
* 下载文件
* @param outPath
* @param urlPath
* @return
*/
public boolean download(String outPath, String urlPath) {
boolean result = false;
RandomAccessFile oSavedFile = null;
InputStream in = null;
try {
HttpURLConnection conn = DownloadUtil.getConnection(urlPath);
int contentLen = conn.getContentLength();
File outFile = mkFile(outPath);
long fileLen = outFile.length();
if(contentLen > fileLen){
conn = DownloadUtil.getConnection(urlPath);
conn.setRequestProperty(RANGE, "bytes="+fileLen+"-");
in = conn.getInputStream();
oSavedFile = new RandomAccessFile(outPath,"rw");
oSavedFile.seek(fileLen);
byte[] b = new byte[204800];
int nRead;
while((nRead=in.read(b,0,204800)) > 0){
oSavedFile.write(b,0,nRead);
}
}
if(contentLen != -1){
result = true;
}
}catch (IOException e) {
System.err.println("file path:"+outPath+"\ndownload url:"+urlPath);
e.printStackTrace();
} finally{
try {
if(oSavedFile!=null){
oSavedFile.close();
}
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}