2010-01-06 94 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); 

這將總是工作,無論你是否部署戰爭或戰爭爆炸閱讀。