在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:49:13  来源:igfitidea点击:

Reading Properties file in Maven Java Project created by maven-archetype-quickstart

javaeclipsemaven

提问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.propertiesis under src/main/resourcestry 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:

另一种解决方案:

  1. Right Click on Project in Eclipse
  2. Select Build Path -> Configure Build Path
  3. In Source tab : Add **/*.properties in "Included" for "src/main/java".
  1. 在 Eclipse 中右键单击项目
  2. 选择构建路径 -> 配置构建路径
  3. 在“源”选项卡中:在“包含”中为“src/main/java”添加 **/*.properties。

The problem was: maven-archetype-quickstart only sets **/*.java in the "Included" list.

问题是:maven-archetype-quickstart 只在“包含”列表中设置 **/*.java。