从类路径目录中获取资源列表 [英] Get a list of resources from classpath directory
问题描述
我正在寻找一种方法来从给定的类路径目录中获取所有资源名称的列表,类似于方法 List
.
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)
.
例如,给定一个包含文件 a.html
、b.html
、c 的类路径目录
和一个子目录 x/y/z
.htmld
,getResourceNames("x/y/z")
应该返回一个 List
包含以下字符串:['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.
我知道我可以用 File
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
实现您自己的扫描仪.例如:
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 框架
使用 PathMatchingResourcePatternResolver
来自 Spring 框架.
Spring Framework
Use PathMatchingResourcePatternResolver
from Spring Framework.
对于巨大的 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屋!