Spring getResources() - > getFile()获取每个资源的路径抛出异常

时间:2018-01-09 15:38:23

标签: java spring

我需要获取给定模式的文件路径列表。

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()抛出异常。

如何以正确的方式从资源获取路径?

2 个答案:

答案 0 :(得分:0)

this.mContext=context是磁盘上的文件系统文件。 (只读)资源位于类路径中,可能包含在jar / ear / war(zip存档)中。

基本的java访问是通过类加载器或类:

File

因此请使用InputStream而不是File。

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

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.

答案 1 :(得分:0)

您正在使用返回java.io.File的getFile()方法。 java.io.File表示文件系统上的文件。 Jar是一个java.io.File。但是该文件中的任何内容都超出了java.io.File的范围,除非未压缩。

改为使用resource.getInputStream()

相关问题