---
title: "Java根据web网站Url下载图片"
author: "水雨田"
date: "2014-07-23T11:01:36Z"
tags: []
categories: ["编程语言"]
slug: "java-web-url"
draft: false
lastmod: "2014-07-23T11:01:36Z"
id: 2095312
url: "https://sleinet.iteye.com/blog/2095312"
---

# Java根据web网站Url下载图片

 

 

[新窗口打开](http://www.itnose.net/detail/6032102.html)[复制代码](http://www.itnose.net/detail/6032102.html)

01. package com.ronniewang.downloadpicture;
02. import java.io.DataInputStream;
03. import java.io.File;
04. import java.io.FileOutputStream;
05. import java.io.IOException;
06. import java.net.MalformedURLException;
07. import java.net.URL;
08. import java.sql.ResultSet;
09. import java.sql.SQLException;
10. import java.util.ArrayList;
11. import com.mysql.jdbc.Connection;
12. import com.mysql.jdbc.Statement;
13. import com.ronniewang.utilities.JdbcUtil;
14. public class DownloadPicture {
15. public static void main(String\[] args) {
16. 测试下载图片：
17. [http://img.iitu.net/img\_lt/58pic/12/50/47/10U58PICMxQ.jpg](http://www.iitu.net/ "www.iitu.net")
18. [http://img.iitu.net/img\_lt/58pic/12/50/47/02C58PIC5hd.jpg](http://www.iitu.net/)
19. [http://img.iitu.net/img\_lt/58pic/12/50/46/92E58PICZM4.jpg](http://www.iitu.net/)
20. DownloadPicture downloadPicture = new DownloadPicture();
21. ArrayList&lt;String&gt; urlList = downloadPicture.readUrlList();
22. downloadPicture.downloadPicture(urlList);
23. }
24. /\**
25. * 传入要下载的图片的url列表，将url所对应的图片下载到本地
26. * @param urlList
27. \*/
28. private void downloadPicture(ArrayList&lt;String&gt; urlList) {
29. URL url = null;
30. int imageNumber = 0;
31. for (String urlString : urlList) {
32. try {
33. url = new URL(urlString);
34. DataInputStream dataInputStream = new DataInputStream(url.openStream());
35. String imageName = imageNumber + ".jpg";
36. FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
37. byte\[] buffer = new byte\[1024];
38. int length;
39. while ((length = dataInputStream.read(buffer)) &gt; 0) {
40. fileOutputStream.write(buffer, 0, length);
41. }
42. dataInputStream.close();
43. fileOutputStream.close();
44. imageNumber++;
45. } catch (MalformedURLException e) {
46. e.printStackTrace();
47. } catch (IOException e) {
48. e.printStackTrace();
49. }
50. }
51. }
52. /\**
53. * 连接mysql数据库，通过查询数据库读取要下载的图片的url列表
54. * @return
55. \*/
56. private ArrayList&lt;String&gt; readUrlList() {
57. ArrayList&lt;String&gt; urlList = new ArrayList&lt;String&gt;();
58. try {
59. Connection connection = (Connection) JdbcUtil.getConnection();
60. Statement statement = (Statement) connection.createStatement();
61. String sql = "select url from url"; //查询语句换位相应select语句
62. ResultSet resultSet = statement.executeQuery(sql);
63. while (resultSet.next()) {
64. String url = resultSet.getString("url");
65. urlList.add(url);
66. System.out.println(url);
67. }
68. JdbcUtil.free(resultSet, statement, connection);
69. } catch (SQLException e) {
70. e.printStackTrace();
71. }
72. return urlList;
73. }
74. }