java实现压缩zip
时间: 2023-07-17 17:11:02 浏览: 58
你可以使用Java提供的ZipOutputStream类来实现压缩zip文件。下面是一个简单的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipCompressionExample {
public static void main(String[] args) {
String sourceFolderPath = "/path/to/source/folder";
String zipFilePath = "/path/to/destination/zipfile.zip";
try {
// 创建ZipOutputStream对象
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
// 调用递归方法压缩文件夹
compressFolder(new File(sourceFolderPath), zos, "");
// 关闭资源
zos.close();
fos.close();
System.out.println("压缩完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void compressFolder(File folder, ZipOutputStream zos, String parentFolder) throws IOException {
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
compressFolder(file, zos, parentFolder + file.getName() + "/");
} else {
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
// 创建ZipEntry对象,并设置名称和路径
ZipEntry ze = new ZipEntry(parentFolder + file.getName());
// 将ZipEntry对象添加到ZipOutputStream中
zos.putNextEntry(ze);
// 读取文件内容并写入压缩文件
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
// 关闭资源
fis.close();
zos.closeEntry();
}
}
}
}
```
在上述代码中,将`sourceFolderPath`设置为要压缩的文件夹的路径,将`zipFilePath`设置为要生成的zip文件的路径。然后使用`ZipOutputStream`创建一个新的zip文件,并递归地将文件夹中的文件添加到压缩文件中。最后关闭资源并输出完成消息。
请注意,这只是一个简单的示例代码,你可能需要根据自己的需求进行更多的错误处理和改进。