List .zip directories without extracting

前端 未结 3 1346
半阙折子戏
半阙折子戏 2020-12-03 06:06

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,

3条回答
  •  隐瞒了意图╮
    2020-12-03 06:29

    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.

提交回复
热议问题