java 列出 .zip 目录而不解压

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11468163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:13:53  来源:igfitidea点击:

List .zip directories without extracting

javazip

提问by Bobi Adzi-Andov

I am building a file explorer in Java and I am listing the files/folders in JTrees. What I am trying to do now is when I get to a zipped folder I want to list its contents, but without extracting it first.

我正在用 Java 构建一个文件资源管理器,并在 JTrees 中列出文件/文件夹。我现在要做的是,当我到达一个压缩文件夹时,我想列出其内容,但不先解压缩。

If anyone has an idea, please share.

如果有人有想法,请分享。

回答by aioobe

I suggest you have a look at ZipFile.entries().

我建议你看看ZipFile.entries()

Here's some code:

这是一些代码:

try (ZipFile zipFile = new ZipFile("test.zip")) {
    Enumeration zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        String fileName = ((ZipEntry) zipEntries.nextElement()).getName();
        System.out.println(fileName);
    }
}

If you're using Java 8, you can avoid the use of the almost deprecated Enumerationclass using ZipFile::streamas follows:

如果您使用的是Java 8,则可以避免使用几乎已弃用的EnumerationZipFile::stream,如下所示:

zipFile.stream()
       .map(ZipEntry::getName)
       .forEach(System.out::println);


If you need to know whether an entry is a directory or not, you could use ZipEntry.isDirectory. You can't get much more information than than without extracting the file (for obvious reasons).

如果您需要知道一个条目是否是一个目录,您可以使用ZipEntry.isDirectory. 与不提取文件相比,您无法获得更多信息(出于显而易见的原因)。



If you want to avoid extracting allfiles,you can extract one file at a time using ZipFile.getInputStreamfor each ZipEntry. (Note that you don't need to store the unpacked data on disk, you can just read the input stream and discard the bytes as you go.

如果您想避免提取所有文件,您可以使用ZipFile.getInputStreamfor each一次提取一个文件ZipEntry。(请注意,您不需要将解压后的数据存储在磁盘上,您只需读取输入流并随时丢弃字节即可。

回答by Aleks G

Use java.util.zip.ZipFileclass and, specifically, its entriesmethod.

使用java.util.zip.ZipFile类,特别是它的entries方法。

You'll have something like this:

你会有这样的事情:

ZipFile zipFile = new ZipFile("testfile.zip");
Enumeration zipEntries = zipFile.entries();
String fname;
while (zipEntries.hasMoreElements()) {
    fname = ((ZipEntry)zipEntries.nextElement()).getName();
    ...
}

回答by vbezhenar

For handling ZIP files you can use class ZipFile. It has method entries()which returns list of entries contained within ZIP file. This information is contained in the ZIP header and extraction is not required.

要处理 ZIP 文件,您可以使用ZipFile类。它有方法entries()返回包含在ZIP 文件中的条目列表。此信息包含在 ZIP 标头中,不需要提取。