Linux教程網
Java程序網絡圖片下載:
- package action;
-
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.FileOutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- public class Getpic {
- public Getpic() {
- }
-
- public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl網絡資源地址 */
- {
-
- try {
- /* 將網絡資源地址傳給,即賦值給url */
- URL url = new URL(fileUrl);
-
- /* 此為聯系獲得網絡資源的固定格式用法,以便後面的in變量獲得url截取網絡資源的輸入流 */
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- DataInputStream in = new DataInputStream(connection.getInputStream());
-
- /* 此處也可用BufferedInputStream與BufferedOutputStream 需要保存的路徑*/
- DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
-
-
- /* 將參數savePath,即將截取的圖片的存儲在本地地址賦值給out輸出流所指定的地址 */
- byte[] buffer = new byte[4096];
- int count = 0;
- while ((count = in.read(buffer)) > 0)/* 將輸入流以字節的形式讀取並寫入buffer中 */
- {
- out.write(buffer, 0, count);
- }
- out.close();/* 後面三行為關閉輸入輸出流以及網絡資源的固定格式 */
- in.close();
- connection.disconnect();
- return true;/* 網絡資源截取並存儲本地成功返回true */
-
- } catch (Exception e) {
- System.out.println(e + fileUrl + savePath);
- return false;
- }
- }
-
- public static void main(String[] args) {
- Getpic pic = new Getpic();/* 創建實例 */
-
- //需要下載的URL
- String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg";
-
- // 截取最後/後的字符串
- String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
-
- //圖片保存路徑
- String filePath = "E:";
-
- /* 調用函數,並且進行傳參 */
- 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);
- }
-
- }
Copyright ©
Linux教程網 All Rights Reserved