从类路径目录中获取资源列表 [英] Get a list of resources from classpath directory
问题描述
我正在寻找一种方法来获取给定类路径目录中所有资源名称的列表,类似于方法 List< String> getResourceNames(String directoryName)
。
I am looking for a way to get a list of all resource names from a given classpath directory, something like a method List<String> getResourceNames (String directoryName)
.
例如,给定一个类路径目录 x / y / z
包含文件 a.html
, b.html
, c.html
和一个子目录 d
, getResourceNames(x / y / z)
应返回列表< String>
包含以下字符串: ['a.html','b.html','c.html','d']
。
For example, given a classpath directory x/y/z
containing files a.html
, b.html
, c.html
and a subdirectory d
, getResourceNames("x/y/z")
should return a List<String>
containing the following strings:['a.html', 'b.html', 'c.html', 'd']
.
它应该适用于文件系统和jar中的资源。
It should work both for resources in filesystem and jars.
I知道我可以用文件
s, JarFile
s和 URL 写一个快速片段
s,但我不想重新发明轮子。我的问题是,鉴于现有的公开库,实现 getResourceNames
的最快方法是什么? Spring和Apache Commons堆栈都是可行的。
I know that I can write a quick snippet with File
s, JarFile
s and URL
s, but I do not want to reinvent the wheel. My question is, given existing publicly available libraries, what is the quickest way to implement getResourceNames
? Spring and Apache Commons stacks are both feasible.
推荐答案
自定义扫描器
实施自己的扫描仪。例如:
Custom Scanner
Implement your own scanner. For example:
private List<String> getResourceFiles(String path) throws IOException {
List<String> filenames = new ArrayList<>();
try (
InputStream in = getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(resource);
}
}
return filenames;
}
private InputStream getResourceAsStream(String resource) {
final InputStream in
= getContextClassLoader().getResourceAsStream(resource);
return in == null ? getClass().getResourceAsStream(resource) : in;
}
private ClassLoader getContextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
Spring Framework
使用来自Spring Framework的 PathMatchingResourcePatternResolver
。
对于巨大的CLASSPATH值,其他技术在运行时可能会很慢。更快的解决方案是使用ronmamo的 Reflections API ,它在编译时预编译搜索。
The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.
这篇关于从类路径目录中获取资源列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!