Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read properties file in web application? [duplicate]

Properties file location is WEB-INF/classes/auth.properties.

I cannot use JSF-specific ways (with ExternalContext) because I need properties file in a service module which doesn't have a dependency on a web-module.

I've already tried

MyService.class.getClassLoader().getResourceAsStream("/WEB-INF/classes/auth.properties"); 

but it returns null.

I've also tried to read it with FileInputStream but it requires the full path what is unacceptable.

Any ideas?

like image 492
Roman Avatar asked Jul 01 '10 18:07

Roman


People also ask

How do I read properties file in Web INF?

Load Properties File from WEB-INF folder To be able to read a properties file stored under WEB-INF folder we will need to access ServletContext. We will do it by injecting the ServletContext into the Root Resource Class with the @Context annotation.

How do I read the URL of a property file?

Steps for reading a properties file in JavaCreate an instance of Properties class. Create a FileInputStream by opening a connection to the properties file. Read property list (key and element pairs) from the input stream using load() method of the Properties class.


2 Answers

Several notes:

  1. You should prefer the ClassLoader as returned by Thread#getContextClassLoader().

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 

    This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

  2. The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.

    classLoader.getResourceAsStream("/auth.properties"); 

    If you opt for using the Thread#getContextClassLoader(), remove the leading /.

The JSF-specific ExternalContext#getResourceAsStream() which uses ServletContext#getResourceAsStream() "under the hoods" only returns resources from the webcontent (there where the /WEB-INF folder is sitting), not from the classpath.

like image 180
BalusC Avatar answered Sep 24 '22 17:09

BalusC


Try this:

MyService.class.getClassLoader().getResourceAsStream("/auth.properties"); 

Reading files with getResourceAsStream looks on the classpath to find the resource to load. Since the classes directory is in the classpath for your webapp, referring to the file as /auth.properties should work.

like image 32
Jesper Avatar answered Sep 21 '22 17:09

Jesper