To read a properties
file in JSF2.0 with Glassfishv3 webserver, which is located at root directory
of my web application, I am using below code-
You should never use java.io.File
to refer web resources. It knows nothing about the context it is sitting in. You should also never use ServletContext#getRealPath()
as it may return null
when the server is configured to expand WAR file in memory instead of on disk, which is beyond your control in 3rd party hosts.
Just use ExternalContext#getResourceAsStream() to get the web resource directly in flavor of an InputStream
. It takes a path relative to the webcontent root.
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
properties.load(ec.getResourceAsStream("/portal-config.properties"));
Update it does not seem to be a web resource at all. You should move the file into the "WebContent" folder as shown in the screenshot. Or, better, the /WEB-INF
folder so that nobody can access it by URL.
properties.load(ec.getResourceAsStream("/WEB-INF/portal-config.properties"));
An alternative would be to put it in the classpath, the "Java source" folder as shown in the screenshot. You don't need to put it in a package, that's optional. Assuming that you didn't put it in a package, then do so:
ClassLoader cl = Thread.currentThread().getContextClassLoader();
properties.load(cl.getResourceAsStream("portal-config.properties"));
(note that the path may not start with a slash!)