java - 从 JAR 中获取文件

标签 java spring resources io

我正在使用 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 文件中的 ResourceFile 引用的正确方法是什么?

最佳答案

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/

相关文章:

java - 如何隐藏/删除/避免系统应用程序(非 UI)在 Android 应用程序抽屉中列出/显示?

java - 插入排序字符串

java - 在 Spring AOP 服务中注入(inject)相同服务实例的最佳方法是什么

java - response.sendError 使用自定义过滤器抛出异常

java - 从 eclipse rcp 引用链接资源

android - 应用在Android中更改语言环境后找不到资源

android - 下载并替换安卓资源文件

java - 使用 MS SQL hibernate

java - JUnit 测试抛出异常的错误形式?

java - RememberMeAuthenticationFilter 和 Java 配置 : Custom implementation to override onSuccessfulAuthentication - how to do it in a clean way?