13

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.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
Bobi Adzi-Andov
  • 191
  • 1
  • 2
  • 8
  • This snippet does exactly what this question aks for: https://stackoverflow.com/a/54861562/5777603 – Alex Feb 25 '19 at 08:01

3 Answers3

25

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

Here's some code:

try (ZipFile zipFile = new ZipFile("test.zip")) {
    Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        String fileName = 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:

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).


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.

Jonathan Schneider
  • 26,852
  • 13
  • 75
  • 99
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 4
    Since java 7, I'd say using NIO via the `FileSystem`, `Path` and `Files` is a much easier (and unified way) or solving this problem. See: http://stackoverflow.com/a/37413531/80779 and http://stackoverflow.com/a/37413128/80779 – LordOfThePigs May 24 '16 at 12:29
10

Use java.util.zip.ZipFile class and, specifically, its entries method.

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();
    ...
}
Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • I have tried this, but i have to know what types of files are in it, this will pretty much just give me the names of the files/folders, i have to know if it is a file, a folder etc. – Bobi Adzi-Andov Jul 13 '12 at 10:07
1

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.

vbezhenar
  • 11,148
  • 9
  • 49
  • 63