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