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
List .zip directories without extracting
提问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 Enumeration
class using ZipFile::stream
as follows:
如果您使用的是Java 8,则可以避免使用几乎已弃用的Enumeration
类ZipFile::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.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.
如果您想避免提取所有文件,您可以使用ZipFile.getInputStream
for each一次提取一个文件ZipEntry
。(请注意,您不需要将解压后的数据存储在磁盘上,您只需读取输入流并随时丢弃字节即可。
回答by Aleks G
Use java.util.zip.ZipFile
class and, specifically, its entries
method.
使用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();
...
}