Search code examples
javafileinputstreamproperties-file

FileNotFoundException when I have given the relative path to the properties file


I am trying to use a properties file to store my DB connection details. It worked when I created a Java application and gave the file name as it is since I placed the properties file in the project root folder.

However, I get a FileNotFoundException when I try this in my Web application. I created a res directory under the project node to hold the properties file. I then gave the path as "res/db.properties" but I get the exception. I also tried placing this file under the configuration files directory but still got the same exception.

Here is my code -

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.util.Properties;

    /**
     *
     * @author aj
     */
    public class getConfigValues {

        public String[] getPropValues() {
            String[] props = new String[4];

            try {
                Properties prop = new Properties();
                String propFileName = "res/db.properties";

                InputStream input = null;

                input = new FileInputStream(propFileName);
                prop.load(input);

                props[0] = prop.getProperty("dbURL");
                props[1] = prop.getProperty("driverClass");
                props[2] = prop.getProperty("user");
                props[3] = prop.getProperty("password");

                return props;

            } catch (FileNotFoundException ip) {

                props[0] = "not found";

                return props;
            } catch (IOException i) {
                props[0] = "IO";

                return props;

            }

        }
    }

What am I doing wrong here?


Solution

    • As a web application you have no way of predicting the current working directory, so using a relative path will always be problematical;
    • Depending upon how you web application is packaged, your property file may not even be a file system object. It may well be a resource buried in a .war file.

    One reliable way for you to access this file is to build it into your web app's WEB-INF directory. You can then access it using javax.servlet.ServletContext.getResourceAsStream("WEB-INF/res/db.properties").

    Alternatively, you could build it into the WEB-INF/classes directory and load it using java.lang.ClassLoader.getResourceAsStream("/res/db.properties").