package com.listings.web.controller; import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileOutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.Date; public class CatchPic { public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl網(wǎng)絡(luò)資源地址 */ { try { /* 將網(wǎng)絡(luò)資源地址傳給,即賦值給url */ URL url = new URL(fileUrl); /* 此為聯(lián)系獲得網(wǎng)絡(luò)資源的固定格式用法,以便后面的in變量獲得url截取網(wǎng)絡(luò)資源的輸入流 */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); /* 此處也可用BufferedInputStream與BufferedOutputStream 需要保存的路徑*/ DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath)); /* 將參數(shù)savePath,即將截取的圖片的存儲在本地地址賦值給out輸出流所指定的地址 */ byte[] buffer = new byte[4096]; int count = 0; while ((count = in.read(buffer)) > 0)/* 將輸入流以字節(jié)的形式讀取并寫入buffer中 */ { out.write(buffer, 0, count); } out.close();/* 后面三行為關(guān)閉輸入輸出流以及網(wǎng)絡(luò)資源的固定格式 */ in.close(); connection.disconnect(); return true;/* 網(wǎng)絡(luò)資源截取并存儲本地成功返回true */ } catch (Exception e) { System.out.PRintln(e + fileUrl + savePath); return false; } } public static void main(String[] args) { CatchPic pic = new CatchPic();/* 創(chuàng)建實例 */ //需要下載的URL String photoUrl = "http://photos.listhub.net/GAMLS/07442715/25?lm=20150426T002920"; // 截取最后/后的字符串 String fileName = new Date().getTime()+".png"; //圖片保存路徑 String filePath = "D:/img/"; /* 調(diào)用函數(shù),并且進行傳參 */ boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName); System.out.println("Run ok!/n Get URL file " + flag); System.out.println(filePath); System.out.println(fileName); } }
新聞熱點
疑難解答