【问题标题】:get File from JAR从 JAR 中获取文件
【发布时间】:2010-08-10 08:39:42
【问题描述】:

我正在使用 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)

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

【问题讨论】:

    标签: java spring resources io


    【解决方案1】:

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

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

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

    【讨论】:

    • @David Williams:只需调用 getInputStream() 而不是 getFile()
    【解决方案2】:

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

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

    【讨论】:

    • 这会给我一个 InputStream,但我真正想要的是一个文件
    • 你会用那个File做什么?
    • 将其传递给需要文件的 API
    • 那么在这种情况下,在一个临时位置创建File
    【解决方案3】:

    快速查看您为资源文档提供的link,内容如下:

    Throws: IOException if the resource cannot be resolved as absolute file path, 
    i.e. if the resource is not available in a file system
    

    也许文本文件在罐子里?在这种情况下,您将不得不使用getInputStream() 来读取其内容。

    【讨论】:

      【解决方案4】:

      只是在此处的答案中添加一个示例。如果您需要 JAR 中的 File(而不仅仅是它的内容),您需要首先从资源中创建一个临时文件。 (以下是用 Groovy 编写的):

          InputStream inputStream = resourceLoader.getResource('/META-INF/foo/file.txt').inputStream
          File tempFile = new File('file.txt')
          OutputStream outputStream = new FileOutputStream(tempFile)
      
          try {
              IOUtils.copy(inputStream, outputStream)
          } catch (IOException e) {
              // Handle exception
          } finally {
              outputStream.close()
          }
      

      【讨论】:

        猜你喜欢
        • 2019-05-23
        • 2018-06-19
        • 2019-11-08
        • 2012-05-16
        • 1970-01-01
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 2017-08-23
        相关资源
        最近更新 更多