package cn.itcast;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//读取资源文件
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test2();
}
//通过servletContext的getReadlPath得到资源的绝对路径后,再通过传统流读取资源文件
public void test2() throws IOException {
String path = this.getServletContext().getRealPath("/WEB-INF/classes/cn/itcast/db.properties");
System.out.println(path);
String filename = path.substring(path.lastIndexOf("\\")+1);
System.out.println("当前读取到资源名称是:"+filename);
FileInputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println(url+username+password);
}
public void test1() throws IOException {
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/itcast/db.properties");
Properties props = new Properties();
props.load(in);
String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println(url+username+password);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}