0

(after searching StackExchange) I cannot figure out why I can load my properties file from a simple Java class with a main() method, but not from a Java servlet. The exception is java.io.FileNotFoundException: resources\dbprops.properties (The system cannot find the path specified)
Could someone please help me load the properties file into my servlet?
(Assume there are other methods and imports in these classes)

Project layout:

project\
    src\
        joerle\
            servlet\
                MyServlet.java
            jdbc\
                JdbcTest.java
    resources\
        dbprops.properties

Simple java class joerle.jdbc.JdbcTest (loads properties):

public class JdbcTest {
    private final String dbPropPath = "resources" + File.separator + "dbprops.properties";
    private Properties props;

    public JdbcTest() {
        try {
            props = new Properties();
            props.load(new FileInputStream(dbPropPath));
            //do stuff
        } catch (FileNotFoundException e) {
            System.err.println("properties file not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("properties file cannot be opened");
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new JdbcTest();
    }
}

Simple java servlet class joerle.servlet.MyServlet (fails to load properties):

public class MyServlet extends HttpServlet {
    private final String dbPropPath = "resources" + File.separator + "dbprops.properties";
    private Properties props;

    public void init(ServletConfig config) throws ServletException {
        try {
            props = new Properties();
            props.load(new FileInputStream(dbPropPath));
            //do stuff
        } catch (FileNotFoundException e) {
            System.err.println("properties file not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("properties file cannot be opened");
            e.printStackTrace();
        }
    }
}

I've already tried:
- Load properties file in servlet?
- Load properties file in Servlet/JSP
and some other solutions...

Thanks in advance!

Community
  • 1
  • 1
Joerle
  • 9
  • 4

1 Answers1

0

Here is the solution I used, which works successfully within a servlet context:

  • Moved properties file to projectRoot/WebContent/WEB-INF/classes/resources/dbprops.properties
  • and called it with this:
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/dbprop.prope‌​rties");

Note where the slashes are if you use this solution. This was a great resource for my trouble-shooting: Where to place and how to read configuration resource files in servlet based application?

Community
  • 1
  • 1
Joerle
  • 9
  • 4