java怎么根据url下载图片

   2025-02-13 8170
核心提示:在Java中,可以使用URL和HttpURLConnection类来下载图片。以下是一个简单的示例代码:import java.io.BufferedInputStream;impor

在Java中,可以使用URLHttpURLConnection类来下载图片。以下是一个简单的示例代码:

import java.io.BufferedInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class ImageDownloader {    public static void main(String[] args) {        String imageUrl = "http://example.com/image.jpg";        String destinationPath = "C:/path/to/save/image.jpg";                try {            URL url = new URL(imageUrl);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setRequestMethod("GET");                        InputStream inputStream = connection.getInputStream();            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);                        FileOutputStream fileOutputStream = new FileOutputStream(destinationPath);                        byte[] buffer = new byte[1024];            int bytesRead;            while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {                fileOutputStream.write(buffer, 0, bytesRead);            }                        fileOutputStream.close();            bufferedInputStream.close();                        System.out.println("Image downloaded successfully.");        } catch (IOException e) {            e.printStackTrace();        }    }}

只需将imageUrl替换为要下载的图片的URL,将destinationPath替换为要保存图片的路径,运行代码即可下载图片。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言