我原计划在验证压缩文件的文件结构时使用 ZipEntry 的 isDirectory() 方法来识别压缩文件是否包含目录。
zip 文件应具有以下文件结构: - 内容/file1.pdf - 文件.xml - 另一个文件.xml
每个 zip 文件都必须有一个文件夹,其中必须包含一些内容。我希望能够依赖 isDirectory() 来检查是否有目录,例如:
//this is part of a unit test which checks the structure of zipped file.
public List<String> unzip(String outpath) {
List<String> fnames = new ArrayList<String>();
try {
FileInputStream fin = new FileInputStream(outpath);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
boolean contentFound = false;
while ((ze = zin.getNextEntry()) != null) {
if(ze.isDirectory()) {
contentFound = true;
}
else {
fnames.add(ze.getName());
zin.closeEntry();
}
}
zin.close();
assertTrue("Content folder not found", contentFound);
} catch(Exception e) {
}
return fnames;
}
尽管提供了包含内容目录的 zip 文件,但当 isDirectory() 从未为真时,我使用以下命令查看正在拾取的内容:
public List<String> unzip(String outpath) {
List<String> fnames = new ArrayList<String>();
try {
FileInputStream fin = new FileInputStream(outpath);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
boolean contentFound = false;
while ((ze = zin.getNextEntry()) != null) {
System.out.println(ze.getName());
fnames.add(ze.getName());
zin.closeEntry();
}
zin.close();
assertTrue("Content folder not found", contentFound);
} catch(Exception e) {
}
return fnames;
}
输出为:
- 内容/文件2.pdf
- 内容/文件1.pdf
- 另一个文件.xml
- 文件.xml
我认为 isDirectory() 永远不会评估为真,因为路径“content/file2.pdf”指向目录中包含的文件而不是目录本身。我不确定我必须做什么才能使用 isDirectory() 自行识别目录。虽然我有解决此问题的方法,但我更愿意理解为什么 isDirectory() 不起作用,因为我预计我可能会错误地解决问题。
识别文件夹存在的变通方法是:
if (zipEntry.getName().contains("content/")) {
currentJob.contentFolderFound();
...
(注:功劳归功于此,原解压方法来源于此方案: Read all files in a folder )
最佳答案
也许有点晚了,但对于那些仍在寻找解决这个问题的好方法的人来说,这是我的答案。
方法(grepCode):
public boolean isDirectory() {
return name.endsWith("/");
}
其中 name
与 ZipEntry.getName()
返回的值相同。
例如,对于 Windows 系统,这应该是 "\\"
,因此 ZipEntry.isDirectory
将始终返回 false。要解决这个问题,您可以使用:
ze.getName().endsWith(File.separator)
代替
ze.isDirectory()
关于java - 使用 isDirectory() 发现 ZipEntry 是否是目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23992509/