0

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
Hassan Bendouj
  • 311
  • 1
  • 8
  • 14

2 Answers2

1

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.

Community
  • 1
  • 1
k_g
  • 4,333
  • 2
  • 25
  • 40
0

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 URLs 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.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166