开发者

How do I read a .properties file without calling its absolute path

I have my .properties file in

com.someOtherpage
 -somefolder
  --theProperties.java  `<--- This guy needs it`
com.somepackage
WEB-INF
 -config
  --project.properties  `<--- Here is where he sits`

when deployed how can I call the properties file with ou开发者_如何学Got calling its absolute path like below

public class theProperties
{
  private static Properties properties = new Properties();

  public theProperties()
  {
  }

  public String get(String attribute) throws Exception
  {
     //what do I need to set up to be able to call this file this way 
     //notice there is no '../../project.properties'
     //                    -----
    InputStream is = theProperties.class.getResourceAsStream("project.properties");
    properties.load(is);

    is.close();

    return properties.getProperty(attribute);
  }
}

The above isn't working, why?


If you put the properties file in the same package as the Class that reads it you specify its path relative to that class, that is if the properties file is in the exact same package as the class loading it you specify the path as project.properties.

If you put the properties file in the default package and the loading class isn't in the default package, you have to specify an absolute path like, /project.properties. Just a reminder no classes should be in the default class path as a general rule.

Either way, your properties file has to be on the classpath which yours isn't. In other words it has to be somewhere in WEB-INF/classes/.

A better solution, but more complex is to use Guice to inject properties and not write your own reader.


here is a nice explanation of how... http://jaitechwriteups.blogspot.com/2007/01/how-to-read-properties-file-in-web.html


Assuming you want to avoid the absolute filepath, not the absolute path within the classpath, you need to do:

theProperties.class.getResourceAsStream("/WEB-INF/config/project.properties")

The forward slash at the front is important. Without it the path is relative to the loading class's package location.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜