【java工具方法】下載網絡圖片到本地

工具方法

	/**
	 * 將網絡地址的圖片下載到本地指定目錄。注意:帶有中文的網絡地址會報錯,需使用URLEncoder.encode(imgPath, "utf-8")對中文字符進行編碼處理
	 * @author 靜心事成
	 * @param imgPath 圖片的網絡地址
	 * @param path 保存圖片的目錄。注意:需包含文件名稱
	 * @throws IOException 
	 * */
	public static void downloadImg(String imgPath, String path) throws IOException {
		// 創建URL連接並打開鏈接
		URLConnection uc = new URL(imgPath).openConnection();
		// 使用URL輸入流,讀取資源,使用輸出流將數據寫入文件
		try (InputStream is = uc.getInputStream(); 
				FileOutputStream out = new FileOutputStream(path);) {
			// 定義1k的緩衝區,避免大量的IO開銷
			byte[] bs = new byte[1024];
			// 讀取到的數據長度
			int len = 0;
			// 讀取數據資源,並寫入文件
			while ((len = is.read(bs)) != -1) out.write(bs, 0, len);
		}
	}

引用的類

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

示例

	public static void main(String[] args) throws UnsupportedEncodingException {
		String param = "支付寶2.jpg";
		String imgPath = "https://free-1253824099.cos.ap-beijing.myqcloud.com/" + URLEncoder.encode(param, "utf-8");
		String path = "D:\\imgPath\\ewm.jpg";
		try {
			downloadImg(imgPath, path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

捐贈

若你感覺讀到這篇文章對你有啓發,能引起你的思考。請不要吝嗇你的錢包,你的任何打賞或者捐贈都是對我莫大的鼓勵。

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