首页 > 基础资料 博客日记
java通过url下载图片保存到本地
2024-05-11 15:00:05基础资料围观409次
Java资料网推荐java通过url下载图片保存到本地这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣
每天一个小方法
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadPicture {
public static void main(String[] args) {
String imageUrl = "https://example.com/path/to/image.jpg";
String savePath = "path/to/save/image.jpg";
try {
downloadPicture(imageUrl, savePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadPicture(String imageUrl, String savePath) throws IOException {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream out = new FileOutputStream(new File(savePath));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
// 下载完成,关闭输入输出流
in.close();
out.close();
connection.disconnect();
System.out.println("图片下载成功,保存路径:" + savePath);
} else {
System.out.println("无法下载图片,响应码:" + responseCode);
}
}
}
文章来源:https://blog.csdn.net/qqasdasdqq/article/details/134536654
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- hot100之普通数组
- 记一次诡异的线上异常赋值排查:代码没错,结果不对
- hot100之子串
- 剑指offer-1、⼆维数组中的查找
- 从尾到头打印链表
- 秒杀/高并发解决方案+落地实现 (技术栈: SpringBoot+Mysql + Redis +RabbitMQ +MyBatis-Plus +Maven + Linux + Jmeter ) -03
- @ModelAttribute、@RequestBody、@RequestParam、@PathVariable 注解对比
- Java 样板代码库 Lombok 使用详解
- wso2~自定义event-publisher
- 数组数量数据数量大 1000万黑名单用户 一百亿基础用户 查询检索思路