使用Java写一个接口,将查到的多个图片链接,下载到一个zip里面
时间: 2024-03-15 15:42:43 浏览: 44
好的,以下是一个简单的Java接口示例,可以将多个图片链接下载到一个zip文件中:
```java
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ImageDownloader {
public static void downloadImagesToZip(List<String> imageUrls, String zipFileName) throws IOException {
// Create a ZipOutputStream to write to the zip file
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
// Iterate through each image URL and download it to a temporary file
for (int i = 0; i < imageUrls.size(); i++) {
String imageUrl = imageUrls.get(i);
String tempFileName = "temp_" + i + ".jpg";
downloadImage(imageUrl, tempFileName);
// Add the temporary file to the zip file
File tempFile = new File(tempFileName);
ZipEntry zipEntry = new ZipEntry(tempFile.getName());
zipOut.putNextEntry(zipEntry);
FileInputStream input = new FileInputStream(tempFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
zipOut.write(buffer, 0, length);
}
input.close();
zipOut.closeEntry();
tempFile.delete();
}
// Close the ZipOutputStream
zipOut.close();
}
private static void downloadImage(String imageUrl, String fileName) throws IOException {
URL url = new URL(imageUrl);
InputStream input = url.openStream();
OutputStream output = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
input.close();
output.close();
}
}
```
这个接口接受一个图片链接列表和一个zip文件名作为参数,然后将每个图片链接下载到一个临时文件中,再将所有临时文件打包进一个zip文件中。调用示例代码如下:
```java
List<String> imageUrls = Arrays.asList(
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg"
);
String zipFileName = "images.zip";
ImageDownloader.downloadImagesToZip(imageUrls, zipFileName);
```
这个示例代码中,我们将三个图片链接放入一个List中,然后将这个List和一个zip文件名传递给ImageDownloader类的静态方法downloadImagesToZip。该方法会自动下载每个图片链接,并将它们打包进一个名为"images.zip"的zip文件中。
阅读全文