閱讀274 返回首頁    go 阿裏雲 go 技術社區[雲棲]


java下載遠程http地址的圖片文件到本地-自動處理圖片是否經過服務器gzip壓縮的問題

java下載遠程http地址的圖片文件到本地-自動處理圖片是否經過服務器gzip壓縮的問題

直接上代碼:

      /**
  * 下載文件到本地
  *
  * @param urlString
  *            被下載的文件地址
  * @param filename
  *            本地文件名
  * @throws Exception
  *             各種異常
  */
 public static void download(String urlString, String filename)
   throws Exception {
  // 構造URL
  URL url = new URL(urlString);
  // 打開連接
  URLConnection con = url.openConnection();
  // 輸入流
  InputStream is = con.getInputStream();

  String code=con.getHeaderField("Content-Encoding");
  System.out.println("cdoe:"+code);
  
  
  if ((null!=code)&& code.equals("gzip"))
  {
   GZIPInputStream gis = new GZIPInputStream(is);
   
   // 1K的數據緩衝
   byte[] bs = new byte[1024];
   // 讀取到的數據長度
   int len;
   // 輸出的文件流
   OutputStream os = new FileOutputStream(filename);
   // 開始讀取
   while ((len = gis.read(bs)) != -1) {
    os.write(bs, 0, len);
   }
   // 完畢,關閉所有鏈接
   gis.close();
   os.close();
   is.close();
   
  }
  else
  {
   
   // 1K的數據緩衝
   byte[] bs = new byte[1024];
   // 讀取到的數據長度
   int len;
   // 輸出的文件流
   OutputStream os = new FileOutputStream(filename);
   // 開始讀取
   while ((len = is.read(bs)) != -1) {
    os.write(bs, 0, len);
   }
   // 完畢,關閉所有鏈接
   os.close();
   is.close();
  }

 }

 

 

 

最後更新:2017-04-02 15:15:09

  上一篇:go 黑客集團揭密--“死亡軍團”
  下一篇:go 個女孩從軟件測試工程師到主管的成長曆程