两种读取资源文件的方法。
db.properties文件中放了三个参数,分别是url、username和password信息。
测试代码:
package cn.edu;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//用ServletContext读取资源文件的方法
public class ServletDemo9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream in =this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
//模板代码(采用传统FileInputStream直接读不好(相对路径),用ServletContext)
Properties props = new Properties();//map
props.load(in);
String url=props.getProperty("url");
String username=props.getProperty("username");
String password=props.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
System.out.println("方法二:");
text2();
}
//通过ServletContext()的getRealPath得到资源的绝对路径后,再通过传统流读取资源文件
//采用ServletContext()利用传统FileInputStream方法读资源文件
//这样得到的路径是真实路径(绝对路径),而不是上面说的相对路径
public void text2() throws IOException{
//这个方法可以拿到资源的名称
String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
FileInputStream in =new FileInputStream(path);
String filename=path.substring(path.lastIndexOf("\\")+1);
System.out.println("资源文件名称为:"+filename);
//System.out.println(path);
//结果D:\apache-tomcat-6.0.24\webapps\day05\WEB-INF\classes\db.properties
Properties props = new Properties();//map
props.load(in);
String url=props.getProperty("url");
String username=props.getProperty("username");
String password=props.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}