开发者

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.getSystemClas开发者_C百科sLoader().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.


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

  • Apache Tomcat 6.0 documenation
    • Class Loader HOW-TO


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.


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");


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜