Mar*_*bel 5 java jar properties maven
我app.properties在我的maven项目下有一个文件,resources如下所示(简化):
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"));
Run Code Online (Sandbox Code Playgroud)
当我从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)
Run Code Online (Sandbox Code Playgroud)
当试图作为JAR文件运行时.
用于创建我使用的组合的jar文件maven-shade-plugin,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>
Run Code Online (Sandbox Code Playgroud)
然后我将main方法中的代码切换到这个:
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"));
Run Code Online (Sandbox Code Playgroud)
并且在运行JAR时设法从文件加载属性,但这次我在IDE中运行时无法加载它们,它以与上面相同的异常结束.
所以我的问题是:如何设置pom.xml文件路径(或文件?),我将能够加载从IDE和JAR文件运行的属性?
提前致谢 :)
您目前的工作方式取决于 java 进程的工作目录。通常,这是启动应用程序时您的命令行(也称为 shell)所指向的。
在大多数 IDE 上,您可以在启动器设置中配置此目录。(对于 Eclipse,它位于第二个选项卡“参数”上)因此您需要目标目录(对于 Eclipse,有一个按钮“工作空间...”)
具体来说,在 intelliJ 中,您可以在“运行/编辑配置”下找到此设置...这将打开一个如下窗口:
您可以在那里编辑工作目录。您只需在末尾添加目标即可。
编辑:实际上你已经在最后添加了 src/main/ressources 。