tags:

views:

124

answers:

4

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.

+1  A: 

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

Pascal Thivent
+1  A: 

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 = 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");
amorfis
+1  A: 

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.

Benoit Courtine
I dont want my property file to sit inside the war file.If I do this way , it works. My requirement is that I need to read the property file outside my war file so that I can deploy the same war file in any environment - uat , prod , etc
Renisha
Always with maven, this is managed as packaging time. You can specify a package profile (uat, prod, etc.). The properties files will be included in the war with the good parameters.
Benoit Courtine
A: 

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

PraveenK