gpt4 book ai didi

java - 使用 Java 压缩和解压缩文件夹和文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:13 27 4
gpt4 key购买 nike

如果我的应用程序想要以动态方式使用 java 压缩结果文件(文件组),Java 中有哪些可用选项?当我浏览时,我有 java.util.zip 包可以使用,但是有没有其他方法可以使用它来实现?

最佳答案

public class FolderZiper {
public static void main(String[] a) throws Exception {
zipFolder("c:\\a", "c:\\a.zip");
}

static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;

fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);

addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}

static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {

File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}

static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);

for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
}

关于java - 使用 Java 压缩和解压缩文件夹和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2271801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com