场景1:在servlet中读取properties配置文件参数
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //通过getServletContext来得到流数据 InputStream properties = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties props = new Properties(); props.load(properties); String user = props.getProperty("username"); String pass = props.getProperty("password"); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //通过getServletContext来得到文件绝对路径,再用平时读文件的方式得到流数据 String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties"); File file = new File(path); FileInputStream in = new FileInputStream(file); Properties props = new Properties(); props.load(properties); String user = props.getProperty("username"); String pass = props.getProperty("password"); }
场景2:不在servlet中,在普通java文件中读取properties配置文件参数
package javaTest; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class testProperties { public static Properties config(){ Properties properties = new Properties(); //通过类装载器得到流数据 InputStream inputStream = testProperties.class.getClassLoader().getResourceAsStream("jdbc.properties"); try { properties.load(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return properties; } }