gpt4 book ai didi

java - 维护 zip 文件中的 Windows 目录

转载 作者:行者123 更新时间:2023-12-01 15:41:53 25 4
gpt4 key购买 nike

我已经查看了最近的相关问题,但找不到解决我的问题的方法。我需要压缩一个包含一堆目录的目录,这些目录都包含内容(基本上是文本文件)。当我打开 zip 时,我想获取相同的目录列表。

我的问题是我可以压缩内容,但我的 zip 文件要么只包含普通文件(没有目录),要么被损坏。有人做过吗?

我发布的代码生成了损坏的或看似空的 zipper 。这是我的方法(总结)

公共(public) zipDir

File dirObj = new File(fileDirectory);
String outFilename = zipDirectory+File.separatorChar+filename+".zip";
log.info("Zip Directory: " + outFilename);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
System.out.println("Creating : " + outFilename);
addDir(dirObj, out);
out.close();

添加目录

File[] files = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];

for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDir(files[i], out);
continue;
}
FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
System.out.println(" Adding: " + files[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}

主要

zipDir(filename, properties);

最佳答案

我找到了解决方案。这段代码正是我所需要的。它压缩目录并维护目录结构。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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 - 维护 zip 文件中的 Windows 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7922152/

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