Java " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞鏍规嵁url涓嬭浇鍥剧墖

扬州沐宇科技
2023-12-09 00:09:41
Java

鍦↗ava涓紝鍙互浣跨敤URL鍜?code>HttpURLConnection绫绘潵涓嬭浇鍥剧墖銆備互涓嬫槸涓€涓畝鍗曠殑绀轰緥浠g爜锛?/p>

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();
        }
    }
}

鍙渶灏?code>imageUrl鏇挎崲涓鸿涓嬭浇鐨勫浘鐗囩殑URL锛屽皢destinationPath鏇挎崲涓鸿淇濆瓨鍥剧墖鐨勮矾寰勶紝杩愯浠g爜鍗冲彲涓嬭浇鍥剧墖銆?/p>

扫码添加客服微信