从JAR获取文件 [英] get File from JAR

查看:183
本文介绍了从JAR获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Spring's Resource abstraction to work with resources (files) in the filesystem. One of the resources is a file inside a JAR file. According to the following code, it appears the reference is valid

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

此时一切都很好,但是当我尝试转换资源文件

At this point, all is well, but then when I try to convert the Resource to a File

templateResource.getFile();

我得到例外

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)

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

What is the correct way to get a File reference to a Resource that exists inside a JAR file?

推荐答案


获取
内存资源的File
引用的正确方法是什么? JAR文件?

What is the correct way to get a File reference to a Resource that exists inside a JAR file?

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

The correct way is not doing that at all because it's impossible. A File represents an actual file on a file system, which a JAR entry is not, unless you have a special file system for that.

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

If you just need the data, use getInputStream(). If you have to satisfy an API that demands a File object, then I'm afraid the only thing you can do is to create a temp file and copy the data from the input stream to it.

这篇关于从JAR获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆