public void downloadImage(String url, String downloadDir, String fileName) { try { URL imageUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection(); connection.setRequestMethod('GET');

    int responseCode = connection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStream inputStream = connection.getInputStream();
        File directory = new File(downloadDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(directory, fileName);
        FileOutputStream outputStream = new FileOutputStream(file);
        
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        
        outputStream.close();
        inputStream.close();
        System.out.println('Image downloaded successfully.');
    } else {
        System.out.println('Error downloading image. Response code: ' + responseCode);
    }
    
    connection.disconnect();
} catch (IOException e) {
    e.printStackTrace();
}

}

Java 图片下载方法 - downloadImage() 实现详解

原文地址: https://www.cveoy.top/t/topic/crcd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录