导入Apache POI时,getResourceAsStream返回null?

时间:2019-11-27 03:08:29

标签: java apache-poi maven-assembly-plugin

我通过使用getResourceAsStream和maven-assembly-plugin添加了<Class-Path>从罐子中读取属性文件。起初它起作用。但是,当我添加Maven依赖项Apache POI时,结果变为null。看来类路径无效。

Java主类

import java.io.IOException;
import java.io.InputStream;

import java.util.Properties;
public class Main {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        InputStream in = Main.class.getClassLoader().getResourceAsStream("config/application.properties");
        properties.load(in);
        System.out.println(properties.getProperty("application.ip"));
    }
}

和pom.xml

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <artifactId> maven-assembly-plugin </artifactId>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <mainClass>Main</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path>
                    </manifestEntries>
                </archive>

            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<dependencies>
     <!--   if add this dependency,I will get null in Main when getResourceAsStream("config/application.properties")-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.0</version>
    </dependency>
</dependencies>

mvn打包后,目标目录结构为:

target
|   poi-demo-1.0-SNAPSHOT-jar-with-dependencies.jar
|   poi-demo-1.0-SNAPSHOT.jar
└───config
      └───application.properties

application.properties是

application.ip=127.0.0.1
application.port=80

没有poi依赖性,我得到以下结果:

$ java -jar poi-demo-1.0-SNAPSHOT-jar-with-dependencies.jar
127.0.0.1

添加poi依赖项时,我得到了空值:

$ java -jar poi-demo-1.0-SNAPSHOT-jar-with-dependencies.jar
Exception in thread "main" java.lang.NullPointerException
        at java.util.Properties$LineReader.readLine(Unknown Source)
        at java.util.Properties.load0(Unknown Source)
        at java.util.Properties.load(Unknown Source)
        at Main.main(Main.java:16)

0 个答案:

没有答案