Why can't my system find my properties file?

17,562

It's much easier to load files using the ClassLoader. Use getClass().getResourceAsStream() to get files that are on your classpath:

InputStream is = Props.class.getResourceAsStream("/src/config/admin.properties");
if(is != null) {
    Properties adminProps = new Properties();
    adminProps.load(is);

Note that the leading slash is very important.

Share:
17,562
haja
Author by

haja

Updated on June 07, 2022

Comments

  • haja
    haja almost 2 years

    I have a properties file called admin.properties under src/config and whenever I run the program it gives me this error:

    java.io.FileNotFoundException: admin.properties (The system cannot find the file specified)

    Here is my code:

    package com.in.props;
    
    public class Props {
        public static void main(String[] args) {
            String filePath = "config/admin.properties";
            Properties adminProps = new Properties();
            adminProps.load(new FileInputStream(filePath));
            String userName = adminProps.getProperty("userName").trim();
            String password = adminProps.getProperty("password").trim();
        }
    }
    

    Here's the properties file, admin.properties:

    userName=test
    password=test
    

    My Props class (in com.in.props) and the admin.properties (in config) are under different directories.

    Project_Root
    -src
     -config
       -admin.properties
     -com
       -in
         -props
           -Props.java
    

    I am not using eclipse and I want to execute this via command prompt.