java按http地址清單下載檔案隊列

來源:互聯網
上載者:User

標籤:

本文實現的功能是通過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地址清單下載檔案隊列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.