我原本计划在验证zip文件的文件结构时使用ZipEntry的isDirectory()方法来识别zip文件是否包含目录。
zip文件应具有以下文件结构: - content / file1.pdf - afile.xml - anotherfile.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;
}
输出为:
我认为isDirectory()永远不会被评估为true,因为路径“content / file2.pdf”指向包含在目录中而不是目录本身的文件。我不确定我要使用isDirectory()自行识别目录。虽然我有一个解决这个问题的方法,但我宁愿理解为什么isDirectory()没有工作,因为我希望我可能会接近错误的问题。
用于识别文件夹存在的工作:
if (zipEntry.getName().contains("content/")) {
currentJob.contentFolderFound();
...
(注意:信用到期时,原始解压方法来自此解决方案: Read all files in a folder)
答案 0 :(得分:1)
虽然重构了这个问题所来自的方法,但是当zipEntry是文件夹本身时,我设法让isDirectory()评估为true(是的!)
我在参考以下指南时进行了重构: http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/
似乎混乱来自于在一段时间内创建ZipEntry(除非你能看到任何其他差异)
ZipInputStream zis;
ZipEntry zipEntry;
try {
zis = new ZipInputStream(filePart.getInputStream());
zipEntry = zis.getNextEntry();
} catch (IOException ioExc) {
//do something;
}
while(zipEntry != null){ //if you run me I will infinitely loop!
String fileName = zipEntry.getName();
System.out.println("I am the directory! " +zipEntry.isDirectory() + " " + zipEntry.getName());
}
答案 1 :(得分:0)
也许有点晚了,但对于那些仍在寻找解决方案的好方法的人来说,这是我的答案。
方法(grepCode):
public boolean isDirectory() {
return name.endsWith("/");
}
其中name
与ZipEntry.getName()
返回的值相同。
对于Windows系统,例如,这应该是"\\"
,因此ZipEntry.isDirectory
将始终返回false。要解决此问题,您可以使用:
ze.getName().endsWith(File.separator)
而不是
ze.isDirectory()