package com.leshiweb.business.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class aaa {
/**
* @param
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//如果批量下载的话 这里写一个循环
download("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F16%2F10%2F29%2F2ac8e99273bc079e40a8dc079ca11b1f.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630579136&t=40b8549a9ecce58efe8fddb3f9c0cc57", "aaaa1.jpg","e:\\");
}
/**
* @param urlString 需要下载的图片网络url路径
* @param filename 下载下来的图片命名
* @param savePath 存储路径
*/
public static void download(String urlString, String filename,String savePath) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
try {
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename+".jpg");
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
} catch (Exception e) {
System.out.println(filename);
}
}
}
java下载图片
最新推荐文章于 2024-04-29 23:37:29 发布