开发者

Cannot read properties file in Java web app?

开发者 https://www.devze.com 2023-04-11 04:20 出处:网络
I am trying to read a properties file in my java web application. I have tried these solution: Where to place and how to read configuration resource files in servlet based application?

I am trying to read a properties file in my java web application. I have tried these solution:

Where to place and how to read configuration resource files in servlet based application?

Howto access properties file from Java EE web application?

But none of them worked for me.

Here is the structure of my app:

Cannot read properties file in Java web app?

The code that reads the properties file is placed in the A class and it did not work even I put the absolute path. A is a normal Java class. But everything worked like a charm if the reading properties code is place in the servlet class (ProcessRequest.java)

Here is the code I have used:

public class A {
    public A() {
        try {
            Properties p = new Properties();
            p.load(this.getClass().getClassLoader().getResourceAsStream("/a.properties"));
            String n = p.getProperty("name");
            Sys开发者_运维问答tem.out.println("name: " + n);
        } catch (Exception ex) {
            Logger.getLogger(A.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Any idea?


You've put it in the servlets package, however you're trying it to get from the classpath root. The leading / makes the path relative to the classpath root.

Fix the path accordingly:

p.load(this.getClass().getClassLoader().getResourceAsStream("/servlets/a.properties"));

or, assuming that the current class is in servlets package already:

p.load(this.getClass().getClassLoader().getResourceAsStream("a.properties"));

Unrelated to the concrete problem, might it later happen that you move the properties file outside the WAR to an external location which allows easy editing of the file without the need to rebuild/redeploy everytime, then I'd suggest to use the thread's context class loader instead of the current class' class loader. It'll work in all circumstances:

p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("servlets/a.properties"));

(note that the path doesn't need to start with / here, because it's always relative to classpath root)


Do you see the properties file under WEB-INF/servlets after building the application. If yes then try using following line.

p.load(getServletContext().getResourceAsStream("/WEB-INF/servlets/a.properties"));

instead of this

p.load(this.getClass().getClassLoader().getResourceAsStream("/a.properties"));
0

精彩评论

暂无评论...
验证码 换一张
取 消