2010-01-06 84 views

回答

17

来加载性能在便携式方式文件,最好的办法是把它放在Web应用程序的类路径(无论是在JAR下WEB-INF/lib/或下WEB-INF/classes/或应用服务器的classpath,如果你想能够编辑该文件而无需重新打包您的Web应用程序)并使用Class#getResourceAsStream(String)

以下代码获取一个InputStream为驻留在同一个包作为servlet在其中执行的代码属性文件:

InputStream inStream = Thread.currentThread().getContextClassLoader() 
       .getResourceAsStream("myfile.properties"); 

然后,load(InputStream)它变成一个Properties对象(跳过异常处理) :

Properties props = new Properties(); 
props.load(inStream); 
1

最好的地方,把它就是网络应用自己的文档根目录下,如“./WEB-INF/myapp.properties”,即相对于在servlet容器解开你的.war.ear文件。您可以直接在.war中提供属性文件。

ServletContext有一个方法getRealPath(String path)返回文件系统中的实际路径。使用真实路径,您可以将其加载到Properties集合中。

更新 您的评论代码试图查找为“/”真正的路径,你应该问你的属性的相对路径文件,如:

String propertiesFilePath = getServletContext().getRealPath("WEB-INF/application.properties"); 
Properties props = properties.load(new FileInputStream(propertiesFilePath)); 
+0

所以我尝试了以下内容: String propertiesFilePath = getServletContext()。getRealPath(“/”)+ File.separator +“WEB-INF”+ File.separator +“application.properties”; properties.load(new FileInputStream(propertiesFilePath)); 我得到一个FileNotFoundException。我不明白我做错了什么。 – Carlosfocker 2010-01-06 20:13:49

2

如果属性文件可以与应用程序一起部署使其成为源代码树的一部分。这将导致属性文件位于WEB-INF/classes文件夹中。

然后可以使用

Properties properties = loadProperties("PropertyFileName.properties", this.getClass()); 
... 

public static Properties loadProperties(String resourceName, Class cl) { 
    Properties properties = new Properties(); 
    ClassLoader loader = cl.getClassLoader(); 
    try { 
     InputStream in = loader.getResourceAsStream(resourceName); 
     if (in != null) { 
      properties.load(in); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return properties; 
} 
4

只要得到ServletContext中的保持和再

InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/log4j.properties"); 
Properties props = new Properties(); 
props.load(stream); 

这将总是工作,无论你是否部署战争或战争爆炸阅读。