调用java 将一个文件夹打包成压缩包
时间: 2024-01-21 19:19:30 浏览: 36
你可以使用 Java 的 ZipOutputStream 类来创建一个压缩包,并将文件夹中的所有文件添加到压缩包中。下面是一个简单的示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class ZipFolder {
public static void main(String[] args) throws Exception {
String folderPath = "path/to/folder";
String zipFilePath = "path/to/output/zip/file.zip";
// 创建 ZipOutputStream 对象
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
// 添加文件到压缩包
File folder = new File(folderPath);
addFilesToZip(folder, folder.getName(), zipOut);
// 关闭 ZipOutputStream 对象
zipOut.close();
}
private static void addFilesToZip(File folder, String parentFolder, ZipOutputStream zipOut) throws Exception {
byte[] buffer = new byte[1024];
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
// 递归添加子文件夹中的文件
addFilesToZip(file, parentFolder + "/" + file.getName(), zipOut);
continue;
}
// 将文件添加到压缩包中
FileInputStream fis = new FileInputStream(file);
zipOut.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zipOut.write(buffer, 0, length);
}
zipOut.closeEntry();
fis.close();
}
}
}
```
其中,`folderPath` 是待压缩的文件夹的路径,`zipFilePath` 是输出的压缩包的路径。`addFilesToZip` 方法递归遍历文件夹中的所有文件,并将它们添加到压缩包中。