歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java程序網絡圖片下載

Java程序網絡圖片下載

日期:2017/3/1 10:28:14   编辑:Linux編程

Java程序網絡圖片下載:

  1. package action;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.io.FileOutputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. public class Getpic {
  8. public Getpic() {
  9. }
  10. public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl網絡資源地址 */
  11. {
  12. try {
  13. /* 將網絡資源地址傳給,即賦值給url */
  14. URL url = new URL(fileUrl);
  15. /* 此為聯系獲得網絡資源的固定格式用法,以便後面的in變量獲得url截取網絡資源的輸入流 */
  16. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  17. DataInputStream in = new DataInputStream(connection.getInputStream());
  18. /* 此處也可用BufferedInputStream與BufferedOutputStream 需要保存的路徑*/
  19. DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
  20. /* 將參數savePath,即將截取的圖片的存儲在本地地址賦值給out輸出流所指定的地址 */
  21. byte[] buffer = new byte[4096];
  22. int count = 0;
  23. while ((count = in.read(buffer)) > 0)/* 將輸入流以字節的形式讀取並寫入buffer中 */
  24. {
  25. out.write(buffer, 0, count);
  26. }
  27. out.close();/* 後面三行為關閉輸入輸出流以及網絡資源的固定格式 */
  28. in.close();
  29. connection.disconnect();
  30. return true;/* 網絡資源截取並存儲本地成功返回true */
  31. } catch (Exception e) {
  32. System.out.println(e + fileUrl + savePath);
  33. return false;
  34. }
  35. }
  36. public static void main(String[] args) {
  37. Getpic pic = new Getpic();/* 創建實例 */
  38. //需要下載的URL
  39. String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg";
  40. // 截取最後/後的字符串
  41. String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
  42. //圖片保存路徑
  43. String filePath = "E:";
  44. /* 調用函數,並且進行傳參 */
  45. boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName);
  46. System.out.println("Run ok!\n Get URL file " + flag);
  47. System.out.println(filePath);
  48. System.out.println(fileName);
  49. }
  50. }
Copyright © Linux教程網 All Rights Reserved