Renisha
Renisha

Reputation: 21

Reading Property file from tomcat webapps folder

I have placed a property file in the webaaps folder of tomcat but not able to access it. My code is

InputStream is = ClassLoader.getSystemResourceAsStream("database.properties");
if(is == null){
    is = ClassLoader.getSystemClassLoader().getResourceAsStream("database.properties");
}
if(is == null){
    is = ClassLoader.getSystemClassLoader().getResourceAsStream("/database.properties");
}
if(is == null){
    is = ClassLoader.getSystemClassLoader().getResourceAsStream("/webapps/database.properties");
}
if(is == null){
    is = ClassLoader.getSystemClassLoader().getResourceAsStream("webapps/database.properties");
}

Still , I am getting input stream as null.

Upvotes: 2

Views: 17369

Answers (4)

amorfis
amorfis

Reputation: 15770

You can't access file that is outside your web application this way. This file is not in your classpath, so you can't get it by "ClassLoader". Put it to your classpath (inside *.war) or access it like this:

File f = new File("/absolute/path/to/your/file");
InputStream is = new FileInputStream(f);

But still tomcat/webapps is not a good place for properties file. Maybe user's home directory? Then you could access it like this:

String home = System.getProperty("user.home");
File f = new File(home + "/yourfile.properties");

Upvotes: 1

PraveenK
PraveenK

Reputation: 1

Need to update classpath with folder name that contains this file. I did that it worked. I did in Eclipse, tomcat and standalone java

java -cp .:$CLASSPATH:some/location/your/config yourclass

Upvotes: 0

Pascal Thivent
Pascal Thivent

Reputation: 570615

The getSystemResourceAsStream method returning null means the resource was not found on the classpath at the specified location. And this makes sense since $TOMCAT_HOME/webapps isn't on the classpath.

So either put that file in a directory that is on the classpath of your application (and if you want to have it outside the war, then you'll have to put it in $CATALINA_HOME/lib - with all the implied consequences) or change your approach (use JNDI to store the properties, use an absolute path, etc).

References

Upvotes: 3

Benoit Courtine
Benoit Courtine

Reputation: 7074

To access properties files by the classpath, I put theses files in "webapp/WEB-INF/classes".

Doing like this is standard, and is a good way to avoid absolute path problems.

If your project has a standard Maven structure, it is managed by Maven :

  • sources are in "src/main/java"
  • properties are in "src/main/resources"

When Maven package the web application, classes are compiled in "webapp/WEB-INF/classes" and resources are copied to the same directory.

Upvotes: 2

Related Questions