public class ZipUtils {
// folderPat 为文件夹路径
// zipFilePath 为压缩包目的路径(必须带后缀名zip)
public static void zipFolder(String folderPath, String zipFilePath) throws IOException {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFilePath);
zos = new ZipOutputStream(fos);
// 递归遍历整个文件夹并添加到压缩包
addFolderToZip("", new File(folderPath), zos);
} finally {
if (zos != null) {
zos.close();
}
if (fos != null) {
fos.close();
}
}
}
/**
* 将文件夹及其中的文件递归添加到压缩流中
*/
private static void addFolderToZip(String parentPath, File folder, ZipOutputStream zos) throws IOException {
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
// 递归添加子文件夹中的文件
addFolderToZip(parentPath + folder.getName() + "/", file, zos);
} else {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
// 新建Zip条目并将输入流加入到Zip包中
ZipEntry zipEntry = new ZipEntry(parentPath + folder.getName() + "/" + file.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
} finally {
if (fis != null) {
fis.close();
}
}
}
}
}
java如何将文件夹压缩成zip压缩包
最新推荐文章于 2025-03-12 09:54:16 发布