Search code examples
javasizedirectorytruezip

TrueZip - How to get Size of a Folder within an Zip Archive


is there a way to get the Size of a folder with TrueZip without doing it myself recursively? I'm concerned about the runtime since I'm dealing with Archives that contain lots of files.

Using TrueZip 7.7.9


Solution

  • OK, here is a simple test using only the standard Java 7 API; it uses the bundled JSR 203 implementation for zips:

    public final class Test
    {
        public static void main(final String... args)
            throws IOException
        {
            final Path zip = Paths.get("/home/fge/t.zip");
    
            final URI uri = URI.create("jar:" + zip.toUri());
    
            try (
                final FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap());
                final DirectoryStream<Path> stream = Files.newDirectoryStream(fs.getPath("/"));
            ) {
                for (final Path entry: stream)
                    System.out.println(Files.size(entry));
            }
        }
    }
    

    The zip above only contains files at the top level, not directories.

    This means that you can use this API to correctly compute the size of files in a zip; without the need to uncompress.

    You use Java 7; therefore, what you want to do is probably to use a FileVisitor which computes the size of all regular files for you.

    Here I have made a crude hack which uses Files.size(); note that in a FileVisitor, when you visit a filesystem entry which is not a directory, you have an instance of BasicFileAttributes coming along from which you can retrieve the size().

    Javadoc here; and use Files.walkFileTree().

    With Java 8, this is much simpler, you could use Files.find() instead.