在 maven-archetype-quickstart 创建的 Maven Java 项目中读取属性文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24779657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading Properties file in Maven Java Project created by maven-archetype-quickstart
提问by Barun
I'm trying to read a properties file using the below code on a Java Project created using Maven ArchetypeId=maven-archetype-quickstart
我正在尝试在使用 Maven ArchetypeId=maven-archetype-quickstart 创建的 Java 项目上使用以下代码读取属性文件
(properties = new Properties()).load(DbCopy.class.getClassLoader()
.getResourceAsStream("config.properties"));
And it throws exception:
它抛出异常:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:284)
at benz.bnp.db.DbCopy.main(DbCopy.java:77)
Thanks for helping !
感谢您的帮助!
采纳答案by ppuskar
Have a look at the target folder, if it contains your properties file. Hopefully it will not contain. To include your property file edit your pom:
查看目标文件夹,如果它包含您的属性文件。希望它不会包含。要包含您的属性文件,请编辑您的 pom:
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/java</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
Add it to your POM.xml and configure the same for your properties file.
将它添加到您的 POM.xml 并为您的属性文件配置相同的内容。
回答by SparkOn
Assuming your config.properties
is under src/main/resources
try something like this :
假设你config.properties
正在src/main/resources
尝试这样的事情:
Properties props = new Properties();
try(InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties")) {
props.load(resourceStream);
}
回答by Barun
Another solution:
另一种解决方案:
- Right Click on Project in Eclipse
- Select Build Path -> Configure Build Path
- In Source tab : Add **/*.properties in "Included" for "src/main/java".
- 在 Eclipse 中右键单击项目
- 选择构建路径 -> 配置构建路径
- 在“源”选项卡中:在“包含”中为“src/main/java”添加 **/*.properties。
The problem was: maven-archetype-quickstart only sets **/*.java in the "Included" list.
问题是:maven-archetype-quickstart 只在“包含”列表中设置 **/*.java。