从maven项目资源文件夹(src / main / resources)加载excel(.xlsx / .xls)文件

时间:2016-06-06 06:55:26

标签: java excel maven apache-poi classpath

这里我试图从maven项目的资源文件夹(src / main / resources)加载excel文件。

文件夹结构

MyWebApp
   |______src/main/java
   |           |____Test.java
   |
   |______src/main/resources
   |            |______test
   |                    |___hello.properties
   |                    |___template.xlsx
   |______target
            |___MyWebApp
                  |____WEB_INF
                         |___classes
                                |__test
                                     |__hello.properties
                                     |__template.xlsx

我的方法

//loading excel file
String resource = "/test/template.xlsx";
System.out.println(this.getClass().getResource(resource) == null); // prints true

//loading properties file
String resource = "/test/hello.properties";
System.out.println(this.getClass().getResource(resource) == null); //prints false

//I have also tried below methods
this.getClass().getClassLoader().getResourceAsStream(resource); //null
new ClassPathResource(resource).getInputStream(); //null

在做了一些谷歌搜索后,我才知道,maven filters binary contents。为了解决这个问题,我修改了pom.xml以允许.xlsx.xls文件扩展名不能使用此help进行过滤。

的pom.xml

<configuration>                
    <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
        <resources>
            <resource>
                 <directory>${basedir}/src/main/resources</directory>
                     <includes>
                         <include>**/*.xlsx</include>
                         <include>**/*.xls</include>
                     </includes>
             </resource>
         </resources>
</configuration>

我能够加载属性文件,但我无法使用上述方法加载excel文件。从我这边我引用了以下两个链接(Rererence-1Reference-2)但没有成功。如果您对此问题有一些想法/想法,请帮助我。

1 个答案:

答案 0 :(得分:1)

在你所链接的the maven documentation page中,有人说:

  

如果您同时拥有文本文件和二进制文件作为资源   建议使用两个单独的文件夹。一个文件夹   src / main / resources(默认值)表示未过滤的资源   和另一个文件夹src / main / resources-filtered为资源   过滤了。

因此,您应该将属性和xlsx文件保存在不同的目录中。

还有information about excluding binary files from filtering

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
      ...
      <nonFilteredFileExtensions>
        <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
        <nonFilteredFileExtension>swf</nonFilteredFileExtension>
      </nonFilteredFileExtensions>
      ...
    </configuration>
 </plugin>
相关问题