gpt4 book ai didi

java - Zip 文件是使用 Windows 路径分隔符创建的

转载 作者:行者123 更新时间:2023-11-30 01:47:56 25 4
gpt4 key购买 nike

我使用下面的代码创建一个 zip 文件。 Zip 已正确创建,然后在我的程序中,我尝试从此文件中获取 zip 条目。如果我打印一个 zip 条目名称,我会得到 Windows 路径分隔符(例如 \a\b\c)。但我需要像 a/b/c 这样的东西。我还没有发布阅读邮政编码条目代码。

public static void zipFolder(File subdirs, String ZipName) throws FileNotFoundException, IOException {

try (FileOutputStream fileWriter = new FileOutputStream(location+File.seperator+ ZipName);
ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
addFolderToZip(subdirs, subdirs, zip);
}
}

private static void addFileToZip(File rootPath, File srcFile, ZipOutputStream zip) throws FileNotFoundException, IOException {

if (srcFile.isDirectory()) {
addFolderToZip(rootPath, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
try (FileInputStream in = new FileInputStream(srcFile)) {
String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
zip.putNextEntry(new ZipEntry(name));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
}

private static void addFolderToZip(File rootPath, File srcFolder, ZipOutputStream zip) throws FileNotFoundException, IOException {
for (File fileName : srcFolder.listFiles()) {
addFileToZip(rootPath, fileName, zip);
}
}

最佳答案

以下代码片段中问题的根本原因:

  String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
zip.putNextEntry(new ZipEntry(name));

File.getPath()方法返回带有系统相关默认名称分隔符的路径。

所以,根据 this

Within a ZIP file, pathnames use the forward slash / as separator, as required by the ZIP spec (4.4.17.1). This requires a conversion from or to the local file.separator on systems like Windows. The API (ZipEntry) does not take care of the transformation, and the need for the programmer to deal with it is not documented.

您应该按以下方式重写此代码段:

  String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
if (File.separatorChar != '/') {
name = name.replace('\\', '/');
}
zip.putNextEntry(new ZipEntry(name));

关于java - Zip 文件是使用 Windows 路径分隔符创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248542/

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