针对某些场景下,面对服务文件大,或者服务端服务器不稳定时使用该模块。功能代码如下:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class MultiFileDownLoad {
private static int position = 0;
public static void doDownLoad(String url){
File targetFile=new File(MultiFileDownLoad.class.getResource("").getFile());
targetFile=targetFile.getParentFile();
targetFile=targetFile.getParentFile();
targetFile=targetFile.getParentFile();
targetFile=targetFile.getParentFile();
targetFile=new File(targetFile.getAbsolutePath()+File.separator+ System.currentTimeMillis()+".wmv");
if(!targetFile.exists()){
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//File targetFile=new File("D://video.wmv");
writeFile(url,targetFile); }
private static InputStream getInputStream(String url,long startPosition){
InputStream inputStream=null;
HttpURLConnection conn=null;
try {
URL filePath=new URL(url);
conn= (HttpURLConnection) filePath.openConnection();
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
long contentLength=conn.getContentLengthLong(); if(startPosition<contentLength){
// 设置断点续传的开始位置
conn.disconnect();
conn=(HttpURLConnection) filePath.openConnection();
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("RANGE","bytes="+startPosition);
contentLength=conn.getContentLengthLong();
System.out.println(contentLength);
inputStream = conn.getInputStream();
}else {
return null;
}
}catch (Exception e){
e.printStackTrace();
}/*finally {
conn.disconnect();
}*/
return inputStream;
}
private static void writeFile(String url,File targetFile){
// 数据读写
byte[] buffer = new byte[1024*1024];
int bytesWritten = 0;
int byteCount = 0;
InputStream inputStream =null;
FileOutputStream fos=null;
long fileLength=0;
try {
fos=new FileOutputStream(targetFile,true);
fileLength=targetFile.length();
inputStream = getInputStream(url,fileLength);
while ((byteCount = inputStream.read(buffer)) != -1) {
fos.write(buffer, bytesWritten, byteCount);
}
}catch (Exception e){
//e.printStackTrace();
try {
inputStream.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
writeFile(url,targetFile);
} }
public static void main(String[] args) {
String filepath = "http://10.84.0.6:2880/fmsdrive%2Fvideo%2F%2Fnews%2F2017%2F10%2F10%D4%C28%C8%D5%D3%CD%CC%EF%B9%E3%BD%C7.wmv";
doDownLoad(filepath);
}
}