我正在使用 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
此时,一切都很好,但是当我尝试将 Resource
转换为 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 文件中的 Resource
的 File
引用的正确方法是什么?
最佳答案
What is the correct way to get a File reference to a Resource that exists inside a JAR file?
正确的方法是根本不这样做,因为这是不可能的。 File
代表文件系统上的实际文件,JAR 条目不是,除非您有专门的文件系统。
如果您只需要数据,请使用 getInputStream()
。如果您必须满足需要 File
对象的 API,那么恐怕您唯一能做的就是创建一个临时文件并将输入流中的数据复制到其中。
关于java - 从 JAR 中获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3447258/