java实现图片批量下载
时间: 2023-07-11 14:59:04 浏览: 144
Java可以使用HttpURLConnection或者HttpClient来下载图片,以下是一个基本的实现示例:
```java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class ImageDownloader {
public static void main(String[] args) {
List<String> urls = new ArrayList<>();
// 添加需要下载的图片链接
urls.add("https://example.com/image1.jpg");
urls.add("https://example.com/image2.jpg");
// ...
for (String url : urls) {
downloadImage(url);
}
}
private static void downloadImage(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// 从链接中解析出文件名
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
bis.close();
is.close();
System.out.println("Downloaded " + fileName);
} else {
System.out.println("Failed to download " + imageUrl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例将会从`urls`列表中读取需要下载的图片链接,然后逐个下载保存到本地文件。你可以根据自己的需求修改代码。
阅读全文