2010-11-26 60 views
2

我需要打开maven jar包内的文件。它是我使用框架的模型配置,库类的构造函数需要传递类型的文件。我可以使用类加载器获取配置文件的路径,而不会有任何问题。但 - 不幸的是 - 文件无法读取jar中的文件。所以我得到java.io.FileNotFoundException。现在我正在寻找解决这个问题的方法。我的计划是解压缩模型配置文件并将其放置在临时目录中。但是,在开始编码之前,我想知道是否有像我这样的问题的其他解决方案。Maven包在jar包内打开文件(作为* File *)

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

+0

您是否需要在构建时或运行时从JAR文件中提取/读取文件?您在下面有两个很好的答案,但都在开发和运行时流程的不同位置完成任务。 – jgifford25 2010-12-20 15:05:26

回答

3

我认为你应该使用JarInputStream,通过JAR条目一一遍历,直到你找到你所需要的。然后只是read()的内容找到了JarEntry

+0

如果图书馆需要一个文件,这将无济于事 – 2010-12-20 13:52:40

4

如果你从一个Maven构建这样做,解压的jar资源使用文件

  • dependency:unpack-dependencies(如果jar是项目的行家dependenies之一)

    <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(如果罐子没有依赖性,但仍可以作为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>