user411103
user411103

Reputation:

Location of config.properties file in Java project

I am trying to read the config.properties file (located in my project root, with my pom.xml, README.md,...). However, I always got "FileNotFound" exceptions. Where should I locate this file in order to work with this code?

/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

Upvotes: 1

Views: 9899

Answers (1)

Jenson
Jenson

Reputation: 118

Here's what I typically do:

  1. Put the property file in /src/main/resources, as mentioned by @Compass

  2. Do a resource filtering in build section of pom.xml to make sure the property file is copied into the package.

    <build>
        ...
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        ...
    </build>
    
  3. Since I'm using Spring to load a property file, I simply write the file path as "classpath:config.properties". But you may need to resort some other technique, such as locating file in a classpath

Upvotes: 2

Related Questions