简体   繁体   中英

load a folder from a jar

I am trying to access a directory inside my jar file. I want to go through every of the files inside the directory itself. I tried using the following:

File[] files = new File("ressources").listFiles();
        for (File file : files) {
            XMLParser parser = new XMLParser(file.getAbsolutePath());
            // some work
        } 

If I test this, it works well. But once I put the contents into the jar, it doesn't because of several reasons. If I use this code, the URL always points outside the jar.

structure of my project :

src 
   controllers
   models
         class that containt traitement
   views
ressources

See this:

How do I list the files inside a JAR file?

Basically, you just use a ZipInputStream to find a list of files (a .jar is the same as a .zip)

Once you know the names of the files, you can use getClass().getResource(String path) to get the URL to the file.

I presume this jar is on your classpath.

You can list all the files in a directory using the ClassLoader .

First you can get a list of the file names then you can get URL s from the ClassLoader for individual files:

public static void main(String[] args) throws Exception {
    final String base = "/path/to/folder/inside/jar";
    final List<URL> urls = new LinkedList<>();
    try (final Scanner s = new Scanner(MyClass.class.getResourceAsStream(base))) {
        while (s.hasNext()) {
            urls.add(MyClass.class.getResource(base + "/" + s.nextLine()));
        }
    }
    System.out.println(urls);
}

You can do whatever you want with the URL - either read and InputStream into memory or copy the InputStream into a File on your hard disc.

Note that this definitely works with the URLClassLoader which is the default, if you are using an applet or a custom ClassLoader then this approach may not work.

NB:

You have a typo - its resources not ressources .

You should use reverse domain name notation for your project, this is the convention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM