简体   繁体   中英

how to list all files in directory - deployment

I have a project structured as below:

Myproject
|--package1
|  |--class1
|--package2
|  |--class2
|--rsc
|  |--images
|     |--image1
      |--image2

My problem is to get all files (images1 & images2) in the images directory after I exported this project as .jar.

After researching the problem I found out that I can use this to access a resource after deployment:

this.getClass().getClassLoader().getResource(path);

But with this method I can just get the resources and not all of the files in that folder.

This is what I tried to do:

File[] files = new File(this.getClass().getClassLoader().getResource("images").getFile()).listFiles();

It works in Eclipse but it doesn't work when I export the project as a .jar.

Is there any solution to this?

It is possible to iterate through the content of a folder inside a jar file. It is however, quite a pain to do so.

Take a look at the JarFile class. You can get all entries of the Jar with the entries() method and then filter them by only look at entries starting with "images/" .

Something like this:

// this is a lengthy work around to figure out the path of the jar file that   
// this application was started from
File pathToJar = new File(Util.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

JarFile jarFile = new JarFile(pathToJar);
java.util.Enumeration enumEntries = jarFile.entries();
while (enumEntries.hasMoreElements()) {
    java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();

    if(!file.getName().contains("images/")) {
        continue;
    }

    // do something with that JarEntry

}

This will NOT work while running the application in Eclipse though (since there is no JarFile there to be scanned).
You need to make a distinction in your code where you either iterate through the directory the normal way or use this way with a Jar file depending on how you launched the application.

If this is all too ugly and/or too much work you should probably also consider to just put that resource folder outside of the jar on the actual file system.
Then you could just access it as you would with any other directory:

File[] files = new File("./rsc/images/").listFiles();

You just have to make sure to include the folder in your deployments or other ways of distributing the application.

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