Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List .zip directories without extracting

Tags:

java

zip

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.

like image 784
Bobi Adzi-Andov Avatar asked Jul 13 '12 09:07

Bobi Adzi-Andov


People also ask

How can I read a Zip file without unzipping it?

zip lists the contents of a ZIP archive to ensure your file is inside. Use the -p option to write the contents of named files to stdout (screen) without having to uncompress the entire archive.

How do I list files in a zip file?

To list/view the contents of a compressed file on a Linux host without uncompressing it (and where GZIP is installed), use the "zcat" command. This is not an answer to my question; it's about zip, not gzip; and not about cat'ing the contents but listing which files are in the zip archive.

How do I open a zip file in Unix without unzipping it?

Using Vim. Vim command can also be used to view the contents of a ZIP archive without extracting it. It can work for both the archived files and folders. Along with ZIP, it can work with other extensions as well, such as tar.

How do I view a zip file in Linux?

To unzip files, open File Manager, as explained in the Zipping Files via GUI section. Right click the ZIP package you'd like to extract, and select Extract Here, as shown below. Once you click Extract Here, Linux will extract all files in the ZIP package in the working directory.


1 Answers

I suggest you have a look at 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:

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.

like image 50
aioobe Avatar answered Oct 02 '22 17:10

aioobe