How to list the files inside a JAR file? How to list the files inside a JAR file? java java

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.


Code that works for both IDE's and .jar files:

import java.io.*;import java.net.*;import java.nio.file.*;import java.util.*;import java.util.stream.*;public class ResourceWalker {    public static void main(String[] args) throws URISyntaxException, IOException {        URI uri = ResourceWalker.class.getResource("/resources").toURI();        Path myPath;        if (uri.getScheme().equals("jar")) {            FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());            myPath = fileSystem.getPath("/resources");        } else {            myPath = Paths.get(uri);        }        Stream<Path> walk = Files.walk(myPath, 1);        for (Iterator<Path> it = walk.iterator(); it.hasNext();){            System.out.println(it.next());        }    }}


erickson's answer worked perfectly:

Here's the working code.

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();List<String> list = new ArrayList<String>();if( src != null ) {    URL jar = src.getLocation();    ZipInputStream zip = new ZipInputStream( jar.openStream());    ZipEntry ze = null;    while( ( ze = zip.getNextEntry() ) != null ) {        String entryName = ze.getName();        if( entryName.startsWith("images") &&  entryName.endsWith(".png") ) {            list.add( entryName  );        }    } } webimages = list.toArray( new String[ list.size() ] );

And I have just modify my load method from this:

File[] webimages = ... BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex].getName() ));

To this:

String  [] webimages = ...BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex]));