這裏以獲取config.properties文件爲例
第一種使用getRealPath()方法
ServletContext context = getServletContext();
String realPath = context.getRealPath("file/config.properties");
Properties properties = new Properties();
FileInputStream inputStream = new FileInputStream(realPath);
properties.load(new InputStreamReader(inputStream));
String name = properties.getProperty("name");
第二種使用getResourceAsStream()方法
ServletContext context = getServletContext();
Properties properties = new Properties();
InputStream asStream = context.getResourceAsStream("file/config.properties");
properties.load(new InputStreamReader(asStream));
String name = properties.getProperty("name");
注意: 此種方式只能獲取項目根目錄下的資源流對象,class文件的流對象需要使用類加載器獲取。
第三種使用類加載器
ServletContext context = getServletContext();
Properties properties = new Properties();
InputStream asStream = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
properties.load(new InputStreamReader(asStream));
String name = properties.getProperty("name");
這裏的相對路徑爲何如此寫: …/…/file/config.properties,可能有人會有些疑惑,但只要你知道相對路徑相對於誰寫的就ok了。留個圖供參考: