Java根据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) {
		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;
	}

}

 

 

 

 

 

JdbcUtil类代码如下:

 

package com.ronniewang.utilities;

import java.sql.*;  
import javax.sql.*;  

/**
 * 连接mysql数据库的工具类,用来作为DownloadPicture进行数据库连接的辅助类
 * @author Administrator
 *
 */
public final class JdbcUtil {  
	//下列配置换成相应内容即可
    private static String url = "jdbc:mysql://localhost:3306/test";
    private static String user = "root";
    private static String password = "123456";  
      
    private JdbcUtil() { }  
      
    static {  
        try {  
            Class.forName("com.mysql.jdbc.Driver");  
        } catch (ClassNotFoundException e) {  
            throw new ExceptionInInitializerError(e);  
        }  
    }  
  
    public static Connection getConnection() throws SQLException{  
        return DriverManager.getConnection(url, user, password);  
    }  
      
    public static void free(ResultSet rs, Statement st, Connection conn) {  
        try {  
            if (rs != null) {  
                rs.close();  
            }  
        } catch (SQLException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (st != null) {  
                    st.close();  
                }  
            } catch (SQLException e) {  
                e.printStackTrace();  
            } finally {  
                if (conn != null) {  
                    try {  
                        conn.close();  
                    } catch (SQLException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
    }  
}  

数据库测试表字段为id和url两列

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是使用 Java 读取图片并将其保存到 MySQL 数据库的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class ImageToMysql { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/db_name"; String user = "username"; String password = "password"; Connection conn = null; PreparedStatement ps = null; FileInputStream fis = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); File image = new File("path/to/image.jpg"); fis = new FileInputStream(image); ps = conn.prepareStatement("INSERT INTO images (id, name, data) VALUES (?, ?, ?)"); ps.setInt(1, 1); ps.setString(2, "image.jpg"); ps.setBinaryStream(3, fis, (int) image.length()); ps.executeUpdate(); System.out.println("Image saved to database."); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fis != null) fis.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } } ``` 在这个示例中,我们将一个名为 `image.jpg` 的图片文件保存到名为 `images` 的 MySQL 数据库中。我们使用 `FileInputStream` 读取图片文件,然后将其作为二进制数据插入到数据库中。 请注意,这只是一个简单的示例,实际应用中可能需要更复杂的处理和错误处理。同时,也需要在数据库中创建适当的表结构来存储图像数据。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值