一、利用ServletContext.getRealPath()[或getResourceAsStream()]
特点:读取应用中的任何文件。只能在web环境下。
private void text3(HttpServletResponse response) throws IOException, IOException{
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db/config/db3.properties");
Properties prop = new Properties();
prop.load(in);
String value = prop.getProperty("db3");
response.getWriter().print(value);
}
二、利用ResourceBundle读取配置文件
特点:可以用在非web环境下。但是只能读取类路径中的properties文件
private void text2(HttpServletResponse response) throws IOException{
ResourceBundle rd = ResourceBundle.getBundle("db.config.db3");
String value = rd.getString("db3");
response.getWriter().print(value);
}
三、利用类加载器读取配置文件(专业)
特点:可以用在非web环境下。可以读取类路径下的任何文件
private void text1(HttpServletResponse response) throws IOException{
ClassLoader cl = ServletDemo1.class.getClassLoader();
InputStream in = cl.getResourceAsStream("com/ztq/servlet/db4.properties");
Properties prop = new Properties();
prop.load(in);
String value = prop.getProperty("db4");
response.getWriter().print(value);
}