从JAR获取文件

Dón*_*nal 12 java io resources spring

我正在使用Spring的Resource抽象来处理文件系统中的资源(文件).其中一个资源是JAR文件中的文件.根据以下代码,似乎引用有效

ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

// The path to the resource from the root of the JAR file
Resource fileInJar = resourcePatternResolver.getResources("/META-INF/foo/file.txt");

templateResource.exists(); // returns true
templateResource.isReadable();  // returns true
Run Code Online (Sandbox Code Playgroud)

在这一点上,一切都很好,但是当我尝试将其转换Resource为a时File

templateResource.getFile();
Run Code Online (Sandbox Code Playgroud)

我得到了例外

java.io.FileNotFoundException: class path resource [META-INF/foo/file.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/m2repo/uic-3.2.6-0.jar!/META-INF/foo/file.txt        
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:198)
at org.springframework.core.io.ClassPathResource.getFile(ClassPathResource.java:174)
Run Code Online (Sandbox Code Playgroud)

获取FileResourceJAR文件中存在的引用的正确方法是什么?

Mic*_*rdt 18

获取对JAR文件中存在的资源的文件引用的正确方法是什么?

正确的方法是不这样做,因为这是不可能的.A File表示文件系统上的实际文件,JAR条目不是,除非您有特殊的文件系统.

如果您只需要数据,请使用getInputStream().如果您必须满足需要File对象的API ,那么我担心您唯一能做的就是创建一个临时文件并将输入流中的数据复制到它.


Boz*_*zho 4

如果您想阅读,只需致电resource.getInputStream()

异常消息非常清楚 - 该文件不驻留在文件系统上,因此您不能拥有实例File。此外——除了阅读其内容之外,还能做什么呢File