user14021516
user14021516

Reputation:

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)

Upvotes: 1

Views: 6703

Answers (2)

Soni
Soni

Reputation: 152

when you do '/' in the begining it will try to read from your root directory. Remove the / and as long as the config.properties is present in src/main/resources, the FileInputStream should be able to pick the config file.

ConfigFileReader.class.getResourceAsStream("config.properties")

Upvotes: 0

Som
Som

Reputation: 1628

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.

Upvotes: 1

Related Questions