我想在类路径中列出具有特定名称的所有文件。我期待多次出现,因此Class.getResource(String)
将无法正常工作。如何找到具有指定名称的类路径中的所有资源?
基本上,我必须在类路径中的任意位置标识具有特定名称(例如:xyz.properties)的所有文件,然后累积读取它们中的元数据。
我想要一些效果Collection<URL> Class.getResources(String)
,但找不到类似的东西。 PS:我没有奢侈的使用任何第三方库,因此需要本土解决方案。
我想在类路径中列出具有特定名称的所有文件。我期待多次出现,因此Class.getResource(String)
将无法正常工作。如何找到具有指定名称的类路径中的所有资源?
基本上,我必须在类路径中的任意位置标识具有特定名称(例如:xyz.properties)的所有文件,然后累积读取它们中的元数据。
我想要一些效果Collection<URL> Class.getResources(String)
,但找不到类似的东西。 PS:我没有奢侈的使用任何第三方库,因此需要本土解决方案。
您可以在类加载器上使用Enumeration getResources(String name)来实现相同。
例如:
Enumeration<URL> enumer = Thread.currentThread().getContextClassLoader().getResources("/Path/To/xyz.properties");
while (enumer.hasMoreElements()) {
System.out.print(enumer.nextElement());
}
我做的是我从classpath中读取Java源文件和使用ClassLoader处理它们。我正在使用follwing代码:
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<URL> 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
}
希望这可以帮助你。
这个类似的问题可以帮助你http://stackoverflow.com/questions/6730580/how-to-read-several-resource-files-with-the-same-name-from-different-jars – logoff