在Java应用程序中读取外部属性文件

问题描述:

我想从Web应用程序的外部加载属性文件。获取属性文件的代码如下所示。在Java应用程序中读取外部属性文件

Properties p = new Properties(); 
p.load(this.getClass().getClassLoader().getResourceAsStream("a.properties")); 

我使用Tomcat服务器,我希望把tomcat的内部属性文件server.Where我可以将其放置在服务器序可用它在类路径,同时运行的应用程序?我并不想改变上面的代码,因为我必须运行同一应用程序服务器淡漠也

+0

我有一个疑问,我如何指定Tomcat/conf/catalina.properties中的propery文件路径? – user2210071

我推荐的第一选择。将a.properties放入类路径中。然后加载:

Properties properties = new Properties(); 
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("a.properties")); 

这种方式可以加载相对于类路径“根”的属性。 Tt建议使用由Thread.currentThread()。getContextClassLoader()为此返回的ClassLoader。

+0

如果我把属性文件放在Web项目之外,例如在d驱动器中。我可以如何在类路径中包含此路径? – user2210071

+0

在这种情况下,您可以使用绝对路径:Properties properties = new Properties(); properties.load(新的FileInputStream(“D:/absolute/path/to/a.properties”); – joan

+0

Sory ..我不想硬编码的路径,我只想给属性文件名只...从tomcat服务器加载它,我可以把它放在tomcat中? – user2210071