【问题标题】:Maven package open a file (as a *File*) inside a jar packageMaven 包在 jar 包中打开一个文件(作为 *File*)
【发布时间】:2011-05-16 06:26:35
【问题描述】:

我需要打开一个 maven jar 包中的文件。它是我使用的框架的模型配置和库类的构造函数,需要传递 File 类型的对象。我可以使用类加载器毫无问题地获取配置文件的路径。但是 - 不幸的是 - File 无法读取 jar 中的文件。所以我得到java.io.FileNotFoundException。现在我正在寻找解决这个问题的方法。我的计划是解压模型配置文件,放到一个临时目录下。但是,在开始编码之前,我想了解是否有其他解决方案可以解决像我这样的问题。

更新:我需要在运行时读取文件。

【问题讨论】:

  • 您是否需要在构建时或运行时从 JAR 文件中提取/读取文件?您在下面有两个很好的答案,但两者都在开发和运行时过程中的不同点完成任务。

标签: file maven-2 jar maven


【解决方案1】:

如果您是从 maven 构建中执行此操作,请使用

将 jar 资源解压缩到文件中
  • dependency:unpack-dependencies(如果 jar 是项目的 maven 依赖项之一)

    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-dependency-plugin</artifactId>
     <executions>
       <execution>
        <id>unpack-dependencies</id>
        <phase>generate-resources</phase>
        <goals>
          <goal>unpack-dependencies</goal>
        </goals>
        <configuration>
          <includeGroupIds>the.groupId</includeGroupIds>
          <includeArtifactIds>the.artifactId</includeArtifactIds>
          <includes>**/path/to/your/resource.txt</includes>
          <outputDirectory>where/do/you/want/it</outputDirectory>
        </configuration>
      </execution>
     </executions>
    </plugin>
    

或使用

  • dependency:unpack(如果 jar 没有依赖项,但仍可作为 maven 工件使用)

    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-dependency-plugin</artifactId>
     <executions>
       <execution>
         <id>unpack</id>
         <phase>generate-resources</phase>
         <goals>
           <goal>unpack</goal>
         </goals>
         <configuration>
           <artifactItems>
             <artifactItem>
               <groupId>the.groupid</groupId>
               <artifactId>the.artifactid</artifactId>
               <version>the.version</version>
               <type>jar</type>
               <outputDirectory>where/do/you/want/it</outputDirectory>
               <includes>**/path/to/your/resource.txt</includes>
             </artifactItem>
           </artifactItems>
         </configuration>
       </execution>
     </executions>
    </plugin>
    

【讨论】:

    【解决方案2】:

    我认为你应该使用JarInputStream,逐个遍历JAR 条目,直到找到你需要的。然后只是找到JarEntryread()内容。

    【讨论】:

    • 如果库需要文件,那将无济于事
    • 好吧,您可以从 JAR 中 read() 并保存到临时的 File。即使在这种情况下,它也比将 JAR 解压到项目中更有效。
    • 感谢您的提示,它让我解决了我的问题。我使用 ClassLoader 查找文件(jar 文件中的路径),将其解压缩到临时目录中,然后将其作为 FILE. 打开
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多