OscarRyz OscarRyz - 1 year ago 99
Java Question

How do I list the files inside a JAR file?

I have this code which reads all the files from a directory.

File textFolder = new File("text_directory");

File [] texFiles = textFolder.listFiles( new FileFilter() {
public boolean accept( File file ) {
return file.getName().endsWith(".txt");

It works great. It fills the array with all the files that end with ".txt" from directory "text_directory".

How can I read the contents of a directory in a similar fashion within a JAR file?

So what I really want to do is, to list all the images inside my JAR file, so I can load them with:


(That one works because the "CompanyLogo" is "hardcoded" but the number of images inside the JAR file could be from 10 to 200 variable length.)


So I guess my main problem would be: How to know the name of the JAR file where my main class lives?

Granted I could read it using

My Structure is like this:

They are like:


Right now I'm able to load for instance "images/image01.png" using:


But only because I know the file name, for the rest I have to load them dynamically.

Answer Source
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
  URL jar = src.getLocation();
  ZipInputStream zip = new ZipInputStream(jar.openStream());
  while(true) {
    ZipEntry e = zip.getNextEntry();
    if (e == null)
    String name = e.getName();
    if (name.startsWith("path/to/your/dir/")) {
      /* Do something with this entry. */
else {
  /* Fail... */

Note that in Java 7, you can create a FileSystem from the JAR (zip) file, and then use NIO's directory walking and filtering mechanisms to search through it. This would make it easier to write code that handles JARs and "exploded" directories.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download