首页 > 基础资料 博客日记
java通过url下载图片保存到本地
2024-05-11 15:00:05基础资料围观615次
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进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- PyTorch KernelAgent 源码解读 ---(3)--- orchestrator
- OpenClaw.NET 外部 CLI 预设系统:从零编写第三方 CLI 集成指南
- Agent Harness 的 Session Tree View:让每一个 Agent 做自己擅长的事情!
- 二、OpenCloudOS Server 9 系统 安装 Nginx
- AI 开发狂飙!.NET 11 Preview 4 原生集成向量搜索 + MCP 模板,EF Core 直接对标 RAG 应用
- Vibe Coding有多强?我只花了一天,就搓出了这个银行开户行查询网站!
- 100条cmd命令大全
- C# ESP32/STM32 轻量 Web 能力库:PicoServer.Nano
- 告别手动计算,SymPy 初识与 Manim 联动
- CC5 反序列化链分析

