简体   繁体   English

Spring getResources()->获取每个资源的路径会在getFile()处引发异常

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

I need to get a list of paths to files for a given pattern. 我需要获取给定模式的文件路径列表。

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

This works when run from IntelliJ, but fails when run from jar file. 从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

It returns proper resource, but resource.getFile() throws exception. 它返回正确的资源,但是resource.getFile()引发异常。

How to get path from Resource in a proper way? 如何以适当的方式从资源获取路径?

File is a file system file on disk. File是磁盘上的文件系统文件。 A (read-only) resource is on the class path, possibly packed in a jar/ear/war (zip archives). (只读) 资源位于类路径上,可能包装在jar / ear / war(zip归档文件)中。

The basic java access is via the class loader or class: 基本的Java访问是通过类加载器或类进行的:

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

So use an InputStream instead of a File. 因此,请使用InputStream而不是File。

With a Spring Resource : 带有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.

A Path inside a resource: 资源内部的路径:

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

You are using the getFile() method which return a java.io.File. 您正在使用getFile()方法,该方法返回java.io.File。 java.io.File represents a file on a file system. java.io.File表示文件系统上的文件。 The Jar is a java.io.File. Jar是一个java.io.File。 But anything within that file is beyond the reach of java.io.File, unless uncompressed. 但是,除非未压缩,否则该文件中的所有内容都超出了java.io.File的范围。

Use resource.getInputStream() instead. 使用resource.getInputStream()代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM