1、配置文件放在src下,在普通class文件中读取
public String sayHello(String name)
{
String path = "config/jdbc_mysql.properties";
Properties props = new Properties();
String error = "";
String context = "";
try{
//获得当前类加载的根目录
context = AccountService.class.getClassLoader().getResource("").toURI().getPath();
//将文件读入文件输入流,存入内存
FileInputStream fis = new FileInputStream(new File(context + path));
//加载文件流的属性
props.load(fis);
}catch(URISyntaxException e){
error +="非法URI";
e.printStackTrace();
}catch(FileNotFoundException e){
error +="找不到文件";
}catch(IOException e){
error +="配置文件加载异常";
}
String driver = props.getProperty("driverClassName");
String user = props.getProperty("user");
return "Hello World " + name +","+ context +","+ driver+"," + user+error;
}
2、在servlet中读取
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//out.append("Served at: ").append(request.getContextPath());
out.write("Served at: " + request.getContextPath());
String propertiesPath = "mysql.properties";
String propertiesPath2 = "WEB-INF/classes/config/jdbc_mysql.properties";
//与上面只是少了WEB-INF/classes/
String propertiesPath3 = "config/jdbc_mysql.properties";
Properties props = new Properties();
Properties props2 = new Properties();
Properties props3 = new Properties();
//获取Servlet上下文的绝对路径
String servletContextPath = this.getServletContext().getRealPath("");
try{
//将文件读入输入流,存入内存
FileInputStream fis = new FileInputStream(new File(servletContextPath + propertiesPath));
//加载文件流的属性
props.load(fis);
}catch(FileNotFoundException e){
out.write("<br>");
out.write("找不到WebContent下的配置文件");
}catch(IOException e){
out.write("WebContent直接下属的配置文件加载失败");
}
try{
FileInputStream fis2 = new FileInputStream(new File(servletContextPath +propertiesPath2));
props2.load(fis2);
}catch(FileNotFoundException e){
out.write("<br>");
out.write("找不到src路径下的配置文件<br/>");
}
out.write("<br/>Servlet上下文:" + servletContextPath+"<br/>");
String haesoadb_user = props.getProperty("haesoadb_user");
String driver = props2.getProperty("driverClassName");//driverClassName
out.write("haesoadb_user:"+ haesoadb_user);
out.write("<br/>");
out.write("driver:"+driver);
String classPath ="";
try{
classPath = TestServlet.class.getClassLoader().getResource("").toURI().getPath();
FileInputStream fis3 = new FileInputStream(new File(classPath +propertiesPath3));
props3.load(fis3);
}catch(Exception e){//URISyntaxException
out.write("<br/>获取路径失败");
}
out.write("<br>通过class获取的绝对路径:" + classPath);
String user = props3.getProperty("user_test");
out.write("<br/>通过class读取配置文件的值:" +user);
}