Search code examples
javaintellij-ideaioexceptionconfiguration-files

Reading from config.file throws FileNotFoundException (no such file or directory)


this is my project structure

- src
-- java
--- utils
---- ConfigFileReader
--- resources
---- config.properties

this is ConfigFileReader class:

public class ConfigFileReader {

    public static String getProperty(String key) {
        Properties properties = new Properties();
        try {
            InputStream inputStream = new FileInputStream("/config.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty(key);
    }
}

and this is my config.properties file:

account_storage_technology=cognito

Unfortunately executing that method throws

java.io.FileNotFoundException: /config.properties (No such file or directory)

  • How can I fix?

Solution

  • You need to keep the resources folder in the same level as src. Like this:

    - src
     - java
      - utils
        - ConfigFileReader
    - resources
      - config.properties
    

    And modify the path as below :

    InputStream inputStream = new FileInputStream("resources/config.properties");
    

    UPDATE : It is not advisable or a good idea to keep properties files inside packages and read it from there. However you can make your code read the file by showing the absolute full path.

    Example :

    InputStream inputStream = new FileInputStream("C:\\Project-Path\\Project-Name\\src\\java\\resources\\config.properties");
    
    // Project-Path : This is the path where your Project Parent folder resides.
    // Project-Name : This is the name of your project.