一、利用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 }