How can I count the number of files in a folder within a JAR?

A Jar file is essentially a Zip file with a manifest.

Jar/Zip files don’t actually have a concept of directories like disks do. They simply have a list of entries that have names. These names may contain some kind path separator and some entries may actually be marked as directories (and tend not to have any bytes associated with them, merely acting as markers)

If you want to find all the resources within a given path, you’re going to have to open the Jar file and inspect it’s entries yourself, for example…

JarFile jf = null;
try {
    String path = "resources";
    jf = new JarFile(new File("dist/ResourceFolderCounter.jar"));
    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
            String name = entry.getName();
            name = name.replace(path + "https://stackoverflow.com/", "");
            if (!name.contains("https://stackoverflow.com/")) {
                System.out.println(name);
            }
        }
    }
} catch (IOException ex) {
    try {
        jf.close();
    } catch (Exception e) {
    }
}

Now, this requires you to know the name of the Jar file you want to use, this may be problematic, as you may wish to list resources from a number of different Jars…

A better solution would be to generate some kind of “resource lookup” file at build time, which contained all the names of the resources that you might need, maybe even keyed to particular names…

This way you could simple use…

BufferedReader reader = null;
try {
    reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsInputStream("/resources/MasterResourceList.txt")));
    String name = null;
    while ((name = br.readLine()) != null) {
        URL url = getClass().getResource(name);
    }
} finally {
    try {
        br.close();
    } catch (Exception exp) {
    }
}

For example…

You could even seed the file with the number of resources 😉

Leave a Comment