java 每十个文件 压缩为一个zip文件
时间: 2024-04-23 18:27:24 浏览: 7
要将每十个文件压缩为一个ZIP文件,你可以在循环中动态创建ZIP文件并将文件添加到该ZIP文件中。以下是一个示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class ZipExample {
public static void main(String[] args) {
String[] filesToCompress = new String[100];
// 假设你已经将需要压缩的文件路径存储在filesToCompress数组中
int batchSize = 10; // 每个ZIP文件包含的文件数量
int zipCount = (int) Math.ceil((double) filesToCompress.length / batchSize);
for (int i = 0; i < zipCount; i++) {
String zipFileName = "compressed_" + (i + 1) + ".zip";
try {
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int j = i * batchSize; j < (i + 1) * batchSize && j < filesToCompress.length; j++) {
String file = filesToCompress[j];
File currentFile = new File(file);
if (currentFile.exists()) {
FileInputStream fis = new FileInputStream(currentFile);
ZipEntry zipEntry = new ZipEntry(currentFile.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
zos.closeEntry();
}
}
zos.close();
System.out.println("文件已成功压缩为:" + zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
上述示例将文件路径存储在`filesToCompress`数组中,并将每十个文件压缩为一个ZIP文件。ZIP文件的命名采用"compressed_1.zip"、"compressed_2.zip"等格式。你可以根据需要调整`batchSize`变量,它表示每个ZIP文件包含的文件数量。确保所需的文件存在,并根据实际情况修改文件路径数组。