[英]How to get Runtime Web Application path?
在我的Web應用程序中,我在web文件夾中使用屬性文件,我需要從同一應用程序中的java文件中引用屬性文件以獲取屬性的值。 我該如何提供路徑? 我需要路徑名而不是URI。 我的代碼如下:
Properties prop = new Properties();
FileInputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream("..\Files\Prop.properties");
prop = new Properties();
prop.load(propertiesStream);
prop.getProperty("id");
propertiesStream.close();
} catch (IOException ioException) {
System.out.println("PropertiesLoader IOException message:" + ioException.getMessage());
}
考慮到它是一個屬性文件,我建議您從類路徑中將其作為ResourceBundle
獲取。
例如,假設您將屬性文件放在此處:
/WEB-INF/classes/MyProperties.properties
您可以使用以下代碼獲取它:
ResourceBundle props = ResourceBundle.getBundle("MyProperties");
或者作為Properties
對象:
Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("MyProperties");
props.load(is);
is.close();
如果你想閱讀包中的屬性文件,那么你應該使用 -
InputStream is = pageContext.getServletContext().getResourceAsStream("/props/env- props.properties");
BufferedReader reader = new BufferedReader(is);
獲得推薦的讀者后,您可以根據需要操作它。 這樣你真的不需要servlet和web應用程序的路徑。 上面的方法將在類路徑中查找資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.