之外我有一个app.properties
文件在我的Maven项目resources
文件夹下,如下所示(简化):负载的.properties从IDE文件,也从JAR
myApp |----src | | | |--main | |--java | | |--ApplicationInitializer.java | | | |--resources | |--app.properties | |---target |--myApp.jar |--app.properties
在ApplicationInitializer
类我想加载从性质该app.properties
文件,下面的代码段:
Properties props = new Properties();
String path = "/app.properties";
try {
props.load(ApplicationInitializer.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(props.getProperty("property"));
这段代码加载性能正常,当我运行它从我的IDE内,但失败例外
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at cz.muni.fi.fits.ApplicationInitializer.main(ApplicationInitializer.java:18)
当试图以JAR文件运行时。
为了创建我使用的maven-shade-plugin
组合的jar文件,maven-jar-plugin
(用于排除属性文件的JAR的外部)和maven-resources-plugin
(用于复制属性文件来特定文件夹)中pom.xml
文件如下所示:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cz.muni.fi.fits.ApplicationInitializer</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<excludes>
<exclude>**/*.properties</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>copy-resource</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
我然后切换的代码在主方法这一个:
Properties props = new Properties();
String path = "./app.properties";
try (FileInputStream file = new FileInputStream(path)) {
props.load(file);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(props.getProperty("property"));
并设法在运行JAR时从文件加载属性,但是这次我无法在IDE中运行时加载它们,它以与上述相同的异常结束。
所以我的问题是:如何设置文件路径(或pom.xml
文件?),我将能够加载从IDE和JAR文件运行的属性?
感谢提前:)
我'看target'你'myApp.jar'和'app.properties'。你可以检查'app.properties'是否在'.jar'文件中? – Kuba
不,这就是为什么我使用'maven-jar-plugin'从jar中排除它 –
为什么你要把属性文件放在jar文件之外?如果你这样做,你不能使用'getResourcesAsStream()'。 – khmarbaise