標籤:
本文實現的功能是通過url列表下載檔案隊列,http url地址如:http://172.16.53.187:8080/LiveDownServer/Media/DownloadFile?path=E%3A%2Fvideofiles%2Ftest123%2Fdevelop%2F2015%2F06%2F12%2Fts%2F12%2F20150612124328.ts 路徑經過了編碼,可以利用java內建函數java.net.URLDecoder.decode進行解碼,解碼之後添加到url列表利用HttpURLConnection迴圈下載,此功能不足之處是無法修改下載檔案的路徑,後續會增加修改下載檔案路徑功能。
//http檔案隊列下載
public void httplistDownload() throws IOException{
String path=ServletActionContext.getRequest().getParameter("path");
//返回ts切片地址清單
URL stSpaceUrl = new URL(path);
HttpURLConnection storageconn = (HttpURLConnection) stSpaceUrl.openConnection();
storageconn.connect();
BufferedReader storageReader = new BufferedReader(new InputStreamReader(storageconn.getInputStream()));
String httpresponse=storageReader.readLine();
httpresponse=httpresponse.substring(1,httpresponse.lastIndexOf("]"));
String[] urlarray=httpresponse.split(", ");
int BUFFER_SIZE= 10240; //緩衝區大小10Kb
String strurl=null;
String filename=null;
String filepath=null;
Vector<String> vdownload=new Vector<String>(); //url列表
Vector<String> vfilename=new Vector<String>(); //檔案名稱列表
for(int i=0;i<urlarray.length;i++){
filepath=java.net.URLDecoder.decode(urlarray[i], "utf-8");
filename=filepath.substring(filepath.lastIndexOf("/")+1);
vdownload.add(filepath); //解碼之後,添加到url列表
vfilename.add(filename); //檔案名稱添加到列表
}
//按列表順序儲存資源
for(int i=0;i<vdownload.size();i++)
{
strurl=(String)vdownload.get(i); //從列表中取出url
filename=(String)vfilename.get(i); //從列表中取出檔案名稱
FileOutputStream fos=null;
BufferedInputStream bis=null;
HttpURLConnection httpUrl=null;
URL url=null;
byte[] buffer=new byte[BUFFER_SIZE];
int size=0;
//建立串連
url=new URL(strurl);
httpUrl=(HttpURLConnection)url.openConnection();
//串連指定的資源
httpUrl.connect();
//擷取網路輸入資料流
bis=new BufferedInputStream(httpUrl.getInputStream());
//建立檔案
fos=new FileOutputStream("E:\\download\\"+filename);
//儲存檔案
while((size=bis.read(buffer))!=-1)
{
fos.write(buffer,0,size);
}
fos.close();
bis.close();
httpUrl.disconnect();
}
}
java按http地址清單下載檔案隊列