config.properties 文件在 Java 项目中的位置

Location of config.properties file in Java project

我正在尝试读取 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

这是我通常做的事情:

  1. 将属性文件放入/src/main/resources,如@Compass

  2. 所述
  3. 在 pom.xml 的构建部分进行资源过滤,以确保 属性 文件被复制到包中。

    <build>
        ...
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        ...
    </build>
    
  4. 因为我使用Spring加载一个属性文件,所以我简单地把文件路径写成"classpath:config.properties"。但是您可能需要求助于其他一些技术,例如 locating file in a classpath