ITeye博客

Java根据web网站Url下载图片

水雨田 · 2014-07-23 11:01 · 编程语言 · Markdown

Java根据web网站Url下载图片

 

 

新窗口打开复制代码

  1. package com.ronniewang.downloadpicture;
  2. import java.io.DataInputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;
  8. import java.sql.ResultSet;
  9. 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
  18. http://img.iitu.net/img_lt/58pic/12/50/47/02C58PIC5hd.jpg
  19. http://img.iitu.net/img_lt/58pic/12/50/46/92E58PICZM4.jpg
  20. DownloadPicture downloadPicture = new DownloadPicture();
  21. ArrayList<String> urlList = downloadPicture.readUrlList();
  22. downloadPicture.downloadPicture(urlList);
  23. }
  24. /**
  25. * 传入要下载的图片的url列表,将url所对应的图片下载到本地
  26. * @param urlList
  27. */
  28. private void downloadPicture(ArrayList<String> 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)) > 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<String> readUrlList() {
  57. ArrayList<String> urlList = new ArrayList<String>();
  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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。