[英]Springboot placed application yaml files in resources/config/ folder, while running the JAR it is not able to find the resources
[英]How to get all files with xml extension placed in resources of springboot application?
我有一個 spring-boot 應用程序,我想收集所有 XML 文件,這些文件位於/src/main/resources
目錄中,其結構如下所示:
-resources
-files
-dir1
-dir11
a.xml
b.xml
-dir2
-dir21
c.xml
-dir3
-dir31
d.xml
I have tried few solutions like using ResourceUtils.getFile
, ClassPathResource
, ResourcePatternResolver
, ClassLoader
but these only work when I am running my application in IDE and dont work if I package my application as jar and deploy it. 我得到以下異常
java.io.FileNotFoundException: class path resource [files] cannot be resolved to absolute file path because it does not reside in the file system:
目錄名(dir1、dir11、dir2 等)和文件名(a.xml、b.xml)不是固定的,因此在代碼中是未知的。
這些目錄和文件可以有任何名稱。
resources/files
是唯一已知的目錄,我想收集此目錄及其子目錄中的所有 xml 文件。
我已經嘗試了幾乎所有在網上找到的解決方案,但似乎對我的用例沒有任何作用。
如何才能做到這一點? 提前致謝。
編輯
您可以獲取已知目錄files
並遞歸列出所有File[]
對象。
如果您使用org.apache.commons.io.FileUtils.listFiles(File directory, String[] extensions, boolean recursive);
我創建了一個幫助器 function 如下所示來包裝String.format
和classpath:
public static File getResourceAsFile(String relativeFilePath) throws FileNotFoundException {
return ResourceUtils.getFile(String.format("classpath:%s",relativeFilePath));
}
並使用它,
String relativeFilePath ="files";
File file =getResourceAsFile(relativeFilePath);
Collection<File> files=FileUtils.listFiles(file,null,true); //
如果您想讀取所有xml
文件,則將第二個參數傳遞為
Collection<File> files=FileUtils.listFiles(file,new String[]{"xml"},true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.