【问题标题】:Location of config.properties file in Java projectJava 项目中 config.properties 文件的位置
【发布时间】:2016-11-21 10:26:49
【问题描述】:

我正在尝试读取 config.properties 文件(位于我的项目根目录中,带有我的 pom.xml、README.md...)。但是,我总是遇到“FileNotFound”异常。我应该在哪里找到此文件才能使用此代码?

/src/main/java/com.example.proj.db/DatabaseManager.java

public DatabaseManager() throws IOException {
  Properties prop = new Properties();
  InputStream input = null;

  input = new FileInputStream("config.properties");
  prop.load(input);
  dbUser = prop.getProperty("dbUser");
}

config.properties

# Database Configuration
dbuser=wooz

【问题讨论】:

  • 通常,我会说 /src/main/resources/ 作为起始位置 <_>
  • 不幸的是,它在那个位置也不起作用,@Compass。同样的错误。
  • 试试getClass().getResourceAsStream("config.properties")(结合@Compass给出的建议)
  • 如果我是你,我宁愿将文件加载为类补丁资源。我会把它放在 /src/main/resources/ 中,正如@Compass 已经提到的,然后通过this.getClass().getResourceAsStream("/config.properties") 加载它。

标签: java eclipse configuration-files properties-file


【解决方案1】:

这是我通常做的事情:

  1. 把属性文件放到/src/main/resources,正如@Compass所说的

  2. 在 pom.xml 的 build 部分进行资源过滤,以确保将属性文件复制到包中。

    <build>
        ...
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        ...
    </build>
    
  3. 由于我使用 Spring 加载属性文件,因此我只需将文件路径写为“classpath:config.properties”。但是您可能需要使用其他一些技术,例如locating file in a classpath

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多