Articles

Navigation ( archives ›› 2009 ›› April ›› 29 ›› How to get the list of files in a directory inside a JAR file )

How to get the list of files in a directory inside a JAR file

Posted on April 29, 2009, 1:33 pm EST

A Java snippet for the day. You cannot simply use a "File" object to grab a list of files from a directory within a JAR file. You would need to iterate through the JAR entries, one by one, (unless I am mistaken). With this approach, you can quickly supply some sort of regex filter, that will return a list of file paths for what your searching.

Code

CODE:
    /**
     * <p>Retrieve a list of filepaths from a given directory within a jar
     * file. If filtered results are needed, you can supply a |filter| 
     * regular expression which will match each entry. 
     *
     * @param filter to filter the results within a regular expression.
     * @return a list of files within the jar |file|
     */
    public static List<String> getJarFileListing(String file, String filter) {
        List<String> files = new ArrayList<String>();
        if (jarLocation == null) {
            return files; // Empty.
        }
        
        // Lets stream the jar file 
        JarInputStream jarInputStream = null;
        try {
            jarInputStream = new JarInputStream(new FileInputStream(jarLocation));
            JarEntry jarEntry;
            
            // Iterate the jar entries within that jar. Then make sure it follows the
            // filter given from the user.
            do {
                jarEntry = jarInputStream.getNextJarEntry();
                if (jarEntry != null) {
                    String fileName = jarEntry.getName();

                    // The filter could be null or has a matching regular expression.
                    if (filter == null || fileName.matches(filter)) {
                        files.add(fileName);
                    }
                }
            }
            while (jarEntry != null);
            jarInputStream.close();
        }
        catch (IOException ioe) {
            throw new RuntimeException("Unable to get Jar input stream from '" + jarLocation + "'", ioe);
        }
        return files;
    }

Examples

a) Find all files under /com/:

CODE:
List<String> files = getJarFileListing("file.jar", "^com/(.*)")
 

a) Find all files under /template/ that has a .tpl extension:

CODE:
List<String> files = getJarFileListing("file.jar", "^template/(.*).tpl$")
 

About this Article:

Comments (0) - Add yours, or View the replies

Categoy (Java)

Views (2090)

Digg it: Digg this article