2017-09-11 126 views
0

的根複製我使用的Maven的組裝插件打造的Java 8項目,並將其打包爲JAR文件的Maven Assembly插件:資源在罐子

我有幾個資源位於src/main/resources(通常的maven資源目錄)。 創建JAR時,將在JAR的根目錄下複製src/main/resources下的所有資源文件。

在代碼中,我試圖使用位於src/main/resources中的FileInputStream打開文件,並且在運行項目而不打包爲JAR文件時效果很好。但是,當我從JAR文件運行項目時,我得到很多FileNotFoundException,因爲我的資源不再在src/main/resources處,而是在${project.basedir}處。

我想讓它們位於JAR文件中的src/main/resources。可能嗎?

我的構建配置情況如下:

<build> 
     <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory> 

     <plugins> 
      <plugin> 
       <!-- Build an executable JAR --> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-jar-plugin</artifactId> 
       <version>3.0.2</version> 
       <configuration> 
        <archive> 

         <manifest> 
          <addClasspath>true</addClasspath> 
          <classpathPrefix>lib/</classpathPrefix> 
          <mainClass>EmployProject.TestAlgo</mainClass> 
         </manifest> 
        </archive> 
        <descriptorRefs> 
         <descriptorRef>jar-with-dependencies</descriptorRef> 
        </descriptorRefs> 
       </configuration> 
      </plugin> 

      <plugin> 
       <artifactId>maven-assembly-plugin</artifactId> 
       <executions> 
        <execution> 
         <phase>package</phase> 
         <goals> 
          <goal>single</goal> 
         </goals> 
        </execution> 
       </executions> 

       <configuration> 
        <archive> 
         <manifest> 
          <addClasspath>true</addClasspath> 
          <classpathPrefix>lib/</classpathPrefix> 
          <mainClass>TestAlgo</mainClass> 
         </manifest> 
        </archive> 

        <descriptorRefs> 
         <descriptorRef>jar-with-dependencies</descriptorRef> 
        </descriptorRefs> 
       </configuration> 
      </plugin> 

     </plugins> 

     <resources> 
      <resource> 
       <directory>${project.basedir}/src/main/resources</directory> 
       <includes> 
        <include>**/*.xml</include> 
       </includes> 
      </resource> 
     </resources> 

    </build> 

編輯

如果這是不可能的,是什麼,在我的代碼,我應該使用它來訪問我的資源文件?

+0

使用Maven插件蔭恩 – Arun

+1

是啊,我爲什麼要使用它呢?有什麼好處,它將如何解決我的問題? –

+0

我的資源文件包含在JAR中。問題在於它們被放在我的項目的根目錄下,並且在代碼中我嘗試使用getClass()。getResource(fileName)訪問它們時,它返回null,因爲它找不到該文件。 –

回答

0

由於@khmarbaise和這個職位:Accessing a Java Resource as a File

我想通了,我用錯了API開放資源。在JAR 資源沒有文件,所以我改變了:

XMLDecoder xmlDec = new XMLDecoder(new InputFileStream(this.getClass().getResourceAsStream(fileName)) 

到:

InputStream in = EnumTools.class.getResourceAsStream(fileName); 
XMLDecoder decoder = new XMLDecoder(in); 
相關問題