从Java项目中的资源文件夹获取所有文件名 [英] Get all file names from resource folder in java project

查看:87
本文介绍了从Java项目中的资源文件夹获取所有文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在手动将歌曲文件名写入String数组,然后将字符串发送到 InputStream = = this.getClass().getResourceAsStream(filename); 来播放歌曲.

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.

我所有的歌曲都位于 resources 文件夹中:

All of my songs are located in resources folder:

是否有Java方法或其他方法来获取这些名称?

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

当我导出为 .jar 时,文件需要工作.

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

我认为我可以使用类似的东西吗?

I thought I could use something like this?

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

是否有一个 listFiles()或其他东西?

Is there a listFiles() or something for that?

谢谢

推荐答案

否,因为类路径在Java中是动态的.任何其他Jar都可以构成一个包,一个类加载器可以像想象中的那样动态,甚至可以根据需要动态创建类或资源.

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.

如果您有一个特定的JAR文件,并且知道该JAR文件中的路径,则只需将该文件视为存档,然后通过 java.util.jar.JarFile 进行访问即可,该文件可以列出文件中的所有条目.

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());
}

如果您想在不知道JAR文件名和路径的情况下执行此操作(例如,通过JAR本身中的类),则需要按照Evgeniy的建议动态获取文件名;只需使用您自己的类名(包括程序包;您的屏幕快照就好像您在默认程序包中,这是个坏主意).

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

这篇关于从Java项目中的资源文件夹获取所有文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆