java 压缩两个zip
时间: 2023-07-08 18:54:01 浏览: 41
您可以使用Java的ZipOutputStream类来压缩两个zip文件。首先,您需要创建一个新的ZipOutputStream对象,并使用putNextEntry()方法为每个zip文件添加一个新的ZipEntry。
以下是一个简单的示例代码,演示如何压缩两个zip文件:
```java
import java.io.*;
import java.util.zip.*;
public class ZipTwoFiles {
public static void main(String[] args) throws Exception {
// 创建一个新的zip输出流
FileOutputStream fos = new FileOutputStream("output.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
// 添加第一个zip文件
ZipFile file1 = new ZipFile("file1.zip");
Enumeration<? extends ZipEntry> entries1 = file1.entries();
while (entries1.hasMoreElements()) {
ZipEntry entry = entries1.nextElement();
zos.putNextEntry(new ZipEntry(entry.getName()));
InputStream is = file1.getInputStream(entry);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
is.close();
}
file1.close();
// 添加第二个zip文件
ZipFile file2 = new ZipFile("file2.zip");
Enumeration<? extends ZipEntry> entries2 = file2.entries();
while (entries2.hasMoreElements()) {
ZipEntry entry = entries2.nextElement();
zos.putNextEntry(new ZipEntry(entry.getName()));
InputStream is = file2.getInputStream(entry);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
is.close();
}
file2.close();
// 完成压缩
zos.close();
fos.close();
}
}
```
请注意,此示例代码中使用的是Java 7及更高版本中的try-with-resources语法,以确保正确关闭输入和输出流。如果您使用的是Java 6或更低版本,则需要手动关闭这些流。