4

对不起,令人困惑的标题。基本上我有一个 ZipFile,里面有一堆 .txt 文件,但也有一个文件夹。我在下面显示的代码是在 zip 条目中找到该文件夹​​。这部分我做得很好。问题是,一旦我找到该文件夹​​,它就是一个 ZipEntry。碰巧没有任何有用的方法来获取该文件夹内的条目。我找到的文件夹中有更多我想要处理的 .txt 文件(这是主要目标)。

zipFile = new ZipFile(zipName);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
    ZipEntry current = entries.nextElement();
    if(current.getName().equals(folderName)) {
         assertTrue(current.isDirectory());
        //Here is where I want to get the files in the folder 
    }
}
4

3 回答 3

4

ZipEntry has a method isDirectory() which

Returns true if this is a directory entry. A directory entry is defined to be one whose name ends with a '/'.

What you'll want to do is iterate over all the the entries (as you are doing) and get the InputStream for those that are inside the directory, ie. that have a path relative to the directory.

Say folderName has the value "/zip/myzip/directory", then a file inside that directory will have a name as "/zip/myzip/directory/myfile.txt". You can use the Java NIO Path api to help you

Path directory = Paths.get("/zip/myzip/directory"); // you get this directory path from the ZipEntry
Path file = Paths.get(current.getName());
if (file.startsWith(directory)) {
   // do your thing
}

You can get the InputStream as

zipFile.getInputStream(current);

Note that paths inside a Zip file will be relative to the root of the Zip location. If the zip is at

C:/Users/You/Desktop/myzip.zip

a folder directly inside the zip with show a path like

directory/
于 2013-08-16T18:49:22.713 回答
-3

类似的东西可以帮助你

final ZipFile zf = new ZipFile(filename);
for (final Enumeration<? extends ZipEntry> e = zf.entries(); e.hasMoreElements();) {
final ZipEntry ze = e.nextElement();
if (!ze.isDirectory()) {
     final String name = ze.getName();
     //.....
    }
}

好好享受 ;-)

于 2014-03-24T15:52:46.210 回答
-3

实际上有一种更简单的方法可以做到这一点。如果您知道当前条目是一个目录,那么在使用 ZipInputStream 时,下一个元素将自动是该目录中的任何内容。例如,假设您的目录结构是这样的:

Dir1/A.txt Dir1/B.txt Dir2/C.txt D.txt

然后要访问以上所有三个,您只需以这种方式进行:

ZipInputStream Zis = new ZipInputStream(in);
ZipEntry entry = Zis.getNextEntry();
while (entry != null) {
    if(!entry.isDirectory)
       //do something with entry  
    //else continue  
    entry = Zis.getNextEntry(); 
}

这将遍历所有文件(按它们列出的顺序),而不必明确检查它们是否是目录,因为您没有对它们做任何不同的事情。

于 2016-04-29T01:47:42.427 回答