簡體   English   中英

Spring getResources()->獲取每個資源的路徑會在getFile()處引發異常

[英]Spring getResources() -> get path for each resource throws exception at getFile()

我需要獲取給定模式的文件路徑列表。

Resource[] resources = context.getResources("classpath*:**/i18n/**/*.properties"); 
...
File file = resources[i].getFile(); /// throws exception
String path = file.getPath(); 

從IntelliJ運行時此方法有效,但從jar文件運行時失敗。

java.io.FileNotFoundException: URL [jar:file:/home/mariusz/.../.../build/libs/app-3.0.0-SNAPSHOT-all.jar!/i18n/test.properties] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/mariusz/../../build/libs/app-3.0.0-SNAPSHOT-all.jar!/i18n/test.properties

它返回正確的資源,但是resource.getFile()引發異常。

如何以適當的方式從資源獲取路徑?

File是磁盤上的文件系統文件。 (只讀) 資源位於類路徑上,可能包裝在jar / ear / war(zip歸檔文件)中。

基本的Java訪問是通過類加載器或類進行的:

URL url = MyApp.class.getResource("..."); // When in a jar: "jar:file:..."
InputStream in = MyApp.class.getResourceAsStream("...");

因此,請使用InputStream而不是File。

帶有Spring Resource

Resource resource = ...;
InputStream in = resource.getURL().openStream();

Path path = Paths.get("/home/mariusz/test.properties");
Files.copy(in, path); // Copies the resource to a real file.

資源內部的路徑:

Path res = Paths.get(resource.getURI());

您正在使用getFile()方法,該方法返回java.io.File。 java.io.File表示文件系統上的文件。 Jar是一個java.io.File。 但是,除非未壓縮,否則該文件中的所有內容都超出了java.io.File的范圍。

使用resource.getInputStream()代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM