我使用下面的代码创建一个 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));
The 文件.getPath() https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getPath()方法返回带有系统相关默认名称分隔符的路径。
所以,根据this https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4244499
在 ZIP 文件中,路径名使用正斜杠 / 作为分隔符,按照ZIP spec https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT(4.4.17.1)。这需要在 Windows 等系统上与本地 file.separator 进行转换。 API (ZipEntry) 不负责转换,并且没有记录程序员处理它的需要。
您应该按以下方式重写此代码片段:
String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
if (File.separatorChar != '/') {
name = name.replace('\\', '/');
}
zip.putNextEntry(new ZipEntry(name));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)