首页 > 基础资料 博客日记

java通过url下载图片保存到本地

2024-05-11 15:00:05基础资料围观216

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进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云