How to list the files inside a JAR file?

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)
      break;
    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.

Leave a Comment