java下载一张图片_java实现从网上下载图片并保存到本地
时间: 2024-01-19 11:02:50 浏览: 74
可以使用 Java 中的 HttpURLConnection 类来从网上下载图片并保存到本地。下面是一个实现示例:
```java
import java.io.*;
import java.net.*;
public class DownloadImage {
public static void main(String[] args) {
String imageUrl = "https://example.com/image.jpg";
String destinationFile = "image.jpg";
try {
URL url = new URL(imageUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConnection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(destinationFile);
int bytesRead = -1;
byte[] buffer = new byte[1024];
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("Image download failed. Response code: " + responseCode);
}
} catch (IOException ex) {
System.out.println("Error during image download: " + ex.getMessage());
}
}
}
```
在上述代码中,`imageUrl` 变量是图片的 URL 地址,`destinationFile` 变量是下载后保存到本地的文件名及路径。该程序使用 HttpURLConnection 类的 `getInputStream()` 方法获取图片数据,然后将其写入到本地文件中。
阅读全文