Get all file names from resource folder in java pr

2019-01-28 08:56发布

问题:

Right now I'm manually writing song file names into a String array, then sending the strings to InputStream is = this.getClass().getResourceAsStream(filename); to play the song.

I would rather loop through all the song names in my resources folder and load them into the array so that each time I add a song, I don't need to manually type it into the array.

All of my songs are located in resources folder:

Is there a java method or something to grab these names?

The files need to work when I export as .jar.

I thought I could use something like this?

InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/");

Is there a listFiles() or something for that?

Thanks

回答1:

No, because the classpath is dynamic in Java. Any additional Jar could contribute to a package, a classloader can be as dynamic as imaginable and could even dynamically create classes or resources on demand.

If you have a specific JAR file and you know the path within that JAR file then you could simply treat that file as archive and access it via java.util.jar.JarFile which lets you list all entries in the file.

JarFile jar = new JarFile("res.jar");
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
    JarEntry entry = entries.nextElement();
    System.out.println(entry.getName());
}

If you want to do this without knowing the JAR filename and path (e.g. by a class within the JAR itself) you need to get the filename dynamically as Evgeniy suggested; just use your own class name (including package; your screenshot looks like you are in default package, which is a bad idea).



回答2:

You can try something like this

Enumeration<URL> e = ClassLoader.getSystemResources("org/apache/log4j");
while (e.hasMoreElements()) {
   URL u = e.nextElement();
   String file = u.getFile();
...

file:/D:/.repository/log4j/log4j/1.2.14/log4j-1.2.14.jar!/org/apache/log4j

extract jar path from here and use JarFile class to know org/apache/log4j contents.

If it is unpacked, you will get straight path and use File.listFIles