java批量下载文件打包
时间: 2023-08-27 16:05:55 浏览: 107
java实现批量下载 多文件打包成zip格式下载
你可以使用Java的URL和IO类来实现批量下载文件,并使用Java的压缩库将下载的文件打包。下面是一个简单的示例代码:
```java
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileDownloader {
public static void main(String[] args) throws IOException {
List<String> fileUrls = new ArrayList<>();
fileUrls.add("http://example.com/file1.txt");
fileUrls.add("http://example.com/file2.txt");
fileUrls.add("http://example.com/file3.txt");
String outputDirectory = "downloaded_files";
String zipFileName = "downloaded_files.zip";
// 创建输出目录
File directory = new File(outputDirectory);
if (!directory.exists()) {
directory.mkdir();
}
// 下载文件到指定目录
for (String url : fileUrls) {
downloadFile(url, outputDirectory);
}
// 打包下载的文件
zipFiles(outputDirectory, zipFileName);
}
private static void downloadFile(String fileUrl, String outputDirectory) throws IOException {
URL url = new URL(fileUrl);
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
try (InputStream in = url.openStream();
FileOutputStream out = new FileOutputStream(outputDirectory + "/" + fileName)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
private static void zipFiles(String directory, String zipFileName) throws IOException {
File dir = new File(directory);
List<String> fileList = new ArrayList<>();
populateFilesList(dir, fileList, dir.getAbsolutePath());
try (FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos)) {
for (String filePath : fileList) {
ZipEntry zipEntry = new ZipEntry(filePath.substring(directory.length() + 1));
zos.putNextEntry(zipEntry);
try (FileInputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
}
}
}
}
private static void populateFilesList(File dir, List<String> fileList, String basePath) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
fileList.add(file.getAbsolutePath());
} else if (file.isDirectory()) {
populateFilesList(file, fileList, basePath);
}
}
}
}
```
在示例代码中,你需要将`fileUrls`列表中的URL替换为你要下载的文件的URL。然后,指定输出目录和打包后的文件名。运行代码后,它将下载文件到指定目录,并将这些文件打包为一个ZIP文件。
阅读全文