package cn.topevery.garden.wapi;
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 ZipFolderExample {
public static void main(String[] args) {
//需要压缩文件路径
String sourceFolderPath = "D:\\docTemplates\\aa";
//压缩后文件所在位置
String zipFilePath = "D:\\docTemplates\\aa.zip";
try {
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
File sourceFolder = new File(sourceFolderPath);
addFolderToZip(sourceFolder, sourceFolder.getName(), zos);
zos.flush();
zos.close();
fos.flush();
fos.close();
System.out.println("Folder zipped successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void addFolderToZip(File folder, String parentFolderName, ZipOutputStream zos) throws IOException {
File[] files = folder.listFiles();
byte[] buffer = new byte[1024];
int bytesRead;
for (File file : files) {
if (file.isDirectory()) {
addFolderToZip(file, parentFolderName + "/" + file.getName(), zos);
continue;
}
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(parentFolderName + "/" + file.getName()));
while ((bytesRead = fis.read(buffer)) > 0) {
zos.write(buffer, 0, bytesRead);
}
zos.closeEntry();
fis.close();
}
}
}
java压缩文件为zip
最新推荐文章于 2024-06-11 10:15:07 发布