如何使用指定的名称查找类路径中的所有资源?

我想列出类路径中具有特定名称的所有文件。 我期待多次出现,因此Class.getResource(String)将不起作用。

基本上我必须在类路径中的任何位置识别具有特定名称的所有文件(例如:xyz.properties),然后累积地读取其中的元数据。

我想要一些效果Collection Class.getResources(String)但找不到类似的东西。

PS:我没有使用任何第三方库的奢侈,因此需要一个本土解决方案。

您可以在类加载器上使用Enumeration getResources(String name)来实现相同的function。

例如:

 Enumeration enumer = Thread.currentThread().getContextClassLoader().getResources("/Path/To/xyz.properties"); while (enumer.hasMoreElements()) { System.out.print(enumer.nextElement()); } 

我所做的是从classpath读取java源文件并使用ClassLoader处理它们。 我正在使用以下代码:

 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert (classLoader != null); // pkgName = "com.comp.pkg" String path = pkgName.replace('.', '/'); // resources will contain all java files and sub-packages Enumeration resources = classLoader.getResources(path); if(resources.hasMoreElements()) { URL resource = resources.nextElement(); File directory = new File(resource.getFile()); // .. process file, check this directory for properties files } 

希望这对你有所帮助。