
9 changed files with 101 additions and 13 deletions
@ -0,0 +1,54 @@ |
|||||
|
package com.yxt.supervise.monitor.biz.util; |
||||
|
|
||||
|
import java.io.*; |
||||
|
import java.net.URL; |
||||
|
import java.net.URLConnection; |
||||
|
|
||||
|
/** |
||||
|
* @author: Haiming Yu |
||||
|
* @createDate:2022/8/16 |
||||
|
* @description: |
||||
|
*/ |
||||
|
public class ImageDownloadUtil { |
||||
|
|
||||
|
/** |
||||
|
* 文件下载到指定路径 |
||||
|
* |
||||
|
* @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://fastdfs-gateway.ys7.com/9cc5/1/capture/003jH5cfuOzAEjMmO0pESFUWhrXTwts.jpg?Expires=1686119490&OSSAccessKeyId=LTAIzI38nEHqg64n&Signature=x3IakXKnd5W1IrAdFAT7y5FCWyE%3D", |
||||
|
"D:\\resources\\download", |
||||
|
"sample.png"); |
||||
|
} |
||||
|
} |
Loading…
Reference in new issue