图片下载是一件很简单的事,那么用java如何实现网络图片下载到本地呢(例如我们从网络上爬取图片)
package org.nutz.common.util;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* @author: Haiming Yu
* @createDate:2022/8/16
* @description:
*/
public class ImageDownload {
/**
* 文件下载到指定路径
*
* @param urlString 链接
* @param savePath 保存路径
* @param filename 文件名
* @throws Exception
*/
public static void download(String urlString, String savePath, String filename) throws IOException {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为20s
con.setConnectTimeout(20 * 1000);
//文件路径不存在 则创建
File sf = new File(savePath);
if (!sf.exists()) {
sf.mkdirs();
}
//jdk 1.7 新特性自动关闭
try (InputStream in = con.getInputStream();
OutputStream out = new FileOutputStream(sf.getPath() + "\\" + filename)) {
//创建缓冲区
byte[] buff = new byte[1024];
int n;
// 开始读取
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
download("https://via.placeholder.com/300.png", "d:\\mnt\\", "sample.png");
}
}