列出.zip目录而不提取 [英] List .zip directories without extracting
问题描述
我正在使用Java构建文件资源管理器,我正在列出JTree中的文件/文件夹。我现在要做的是当我到达一个压缩文件夹时,我想列出其内容,但不先将其解压缩。
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.
如果有人有想法,请分享。
If anyone has an idea, please share.
推荐答案
我建议你看看 ZipFile.entries()
。
I suggest you have a look at ZipFile.entries()
.
以下是一些代码:
try (ZipFile zipFile = new ZipFile("test.zip")) {
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
String fileName = ((ZipEntry) zipEntries.nextElement()).getName();
System.out.println(fileName);
}
}
如果您使用的是 Java 8 ,您可以使用 ZipFile :: stream
避免使用几乎已弃用的 Enumeration
类,如下所示:
If you're using Java 8, you can avoid the use of the almost deprecated Enumeration
class using ZipFile::stream
as follows:
zipFile.stream()
.map(ZipEntry::getName)
.forEach(System.out::println);
如果您需要知道某个条目是否是目录与否,你可以使用 ZipEntry.isDirectory
。除了没有提取文件之外,你得到的信息不多(出于显而易见的原因)。
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).
如果你想要避免提取所有文件,您可以使用 ZipFile.getInputStream
对于每个 ZipEntry
。 (请注意,您不需要将解压缩的数据存储在磁盘上,您可以随时读取输入流并丢弃字节。
If you want to avoid extracting all files, you can extract one file at a time using ZipFile.getInputStream
for 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.
这篇关于列出.zip目录而不提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!