[英]How to load resources from classpath matching a pattern with Quarkus
我正在嘗試從類路徑加載包含特定模式(例如 *.properties)的所有資源。 因此我嘗試使用
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
ArrayList<URL> resources = Collections.list(classLoader.getResources(""));
resources.add(classLoader.getResource("org"));
在下一步中,我遍歷了 URL 資源列表,創建了適當的java.nio.FileSystem
並使用PathMatcher
查找所需的資源。
由於以下原因,此解決方案不起作用:
classloader.getResource()
不適用於""
, null
或/
Quarkus 有沒有辦法使用模式從類路徑加載資源列表。
提前致謝並致以最誠摯的問候
ClassLoader.getResources("name")
枚舉所有具有名稱的資源。 但不枚舉名為“名稱”的目錄中的“文件”。
例如,您可能需要包含文件 /my.properties 的/my.properties
。 在這種情況下,方法ClassLoader.getResources("my.properties")
為每個文件返回兩個 URL。
我通過以下方式解決了這個問題:
首先,我將此 maven 依賴項添加到我的項目中:
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
該庫提供了一個名為ClasspathHelper
的 class,已按照以下代碼片段中的說明使用。
Collection<URL> classpathURLs = ClasspathHelper.forPackage("org", (ClassLoader[]) null);
Path path = null;
FileSystem fileSystem = null;
for (URL classpathURL : classpathURLs) {
try {
if (classpathURL.toString().startsWith("jar:file:/")) {
fileSystem = FileSystems.newFileSystem(classpathURL.toURI(), new HashMap<>());
path = fileSystem.getPath("/");
} else {
fileSystem = FileSystems.getDefault();
path = fileSystem.getPath(classpathURL.getPath());
}
PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:**/*.properties");
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(path)) {
String resourceName = (path.getClass().getName().contains("ZipPath") ? path.toString() : path.toFile().getName());
// resource found - do further processing
}
return FileVisitResult.CONTINUE;
}
});
} catch (URISyntaxException | IOException ex) {
// handle exceptions
}
}
如您所見, classpathURL
的列表將從classpathHelper
返回。 這些 URL 以jar:file:/
或以file:/
。 對於每種情況,都會創建一個適當的FileSystem
和Path
。 最后,將使用java.nio.PathMatcher
和SimpleFileVisitor
來查找所需的資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.