Java根据web网站Url下载图片
- package com.ronniewang.downloadpicture;
- import java.io.DataInputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import com.mysql.jdbc.Connection;
- import com.mysql.jdbc.Statement;
- import com.ronniewang.utilities.JdbcUtil;
- public class DownloadPicture {
- public static void main(String[] args) {
- 测试下载图片:
- http://img.iitu.net/img_lt/58pic/12/50/47/10U58PICMxQ.jpg
- http://img.iitu.net/img_lt/58pic/12/50/47/02C58PIC5hd.jpg
- http://img.iitu.net/img_lt/58pic/12/50/46/92E58PICZM4.jpg
- DownloadPicture downloadPicture = new DownloadPicture();
- ArrayList<String> urlList = downloadPicture.readUrlList();
- downloadPicture.downloadPicture(urlList);
- }
- /**
- * 传入要下载的图片的url列表,将url所对应的图片下载到本地
- * @param urlList
- */
- private void downloadPicture(ArrayList<String> urlList) {
- URL url = null;
- int imageNumber = 0;
- for (String urlString : urlList) {
- try {
- url = new URL(urlString);
- DataInputStream dataInputStream = new DataInputStream(url.openStream());
- String imageName = imageNumber + ".jpg";
- FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
- byte[] buffer = new byte[1024];
- int length;
- while ((length = dataInputStream.read(buffer)) > 0) {
- fileOutputStream.write(buffer, 0, length);
- }
- dataInputStream.close();
- fileOutputStream.close();
- imageNumber++;
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 连接mysql数据库,通过查询数据库读取要下载的图片的url列表
- * @return
- */
- private ArrayList<String> readUrlList() {
- ArrayList<String> urlList = new ArrayList<String>();
- try {
- Connection connection = (Connection) JdbcUtil.getConnection();
- Statement statement = (Statement) connection.createStatement();
- String sql = "select url from url"; //查询语句换位相应select语句
- ResultSet resultSet = statement.executeQuery(sql);
- while (resultSet.next()) {
- String url = resultSet.getString("url");
- urlList.add(url);
- System.out.println(url);
- }
- JdbcUtil.free(resultSet, statement, connection);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return urlList;
- }
- }