JAVA 根據URL 下載圖片

原文鏈接:https://blog.csdn.net/sinat_37795871/article/details/83992351

導入的包都是java.io中的 

/**
 * 下載遠程圖片
 * @param remPicURL 遠程圖片文件路徑
 * @param savePath  本地保存路徑
 */
public static Map<String, Object> download(String remPicURL ,String savePath){
	Map<String, Object> res = new HashMap<String, Object>();
	String code = "1";
	String msg = "下載成功:圖片存放在:C://";
	// 構造URL
	InputStream is = null;
	OutputStream os = null;
	try {
		java.net.URL url = new java.net.URL(remPicURL);
		 // 打開連接
	    URLConnection con = url.openConnection();
	    // 輸入流
	    is = con.getInputStream();
	    // 1K的數據緩衝
	    byte[] bs = new byte[1024];
	    // 讀取到的數據長度
	    int len;
	    // 輸出的文件流
	    os = new FileOutputStream(savePath);
	    // 開始讀取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	} catch (Exception e) {
		e.printStackTrace();
		code = "0";
		msg = "下載失敗";
	} finally {
		if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
          	  e.printStackTrace(); 
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
          	  e.printStackTrace(); 
            }
        }
	}
    
    res.put("code", code);
    res.put("msg", msg);
    return res;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章