共計 1075 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 URL
和HttpURLConnection
類來下載圖片。以下是一個簡單的示例代碼:
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
替換為要保存圖片的路徑,運行代碼即可下載圖片。
丸趣 TV 網(wǎng) – 提供最優(yōu)質的資源集合!
正文完
發(fā)表至: Java
2023-12-09