/*
* 在Servlet中读取文件配置信息的相关操作
* http://blog.csdn.net/strawberry2013
* 2013-6-11
* */
package cn.baidu;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//在Servlet中读取文件信息
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
//this.getServletContext().getResourceAsStream(为当前web应用的根目录)
Properties props = new Properties();
props.load(in);
Enumeration<Object> keys = props.keys();
while(keys.hasMoreElements()){
String key = (String) keys.nextElement();
response.getOutputStream().println(key +"="+ props.getProperty(key));
}
Person p = new Person();
p.show();
}
}
//在非servlet中读取文件信息
class Person{
public void show() throws IOException{
//1.通过类装载器获得类所在的目录this.getClass().getClassLoader().getResource(类当前目录)
String path = this.getClass().getClassLoader().getResource("db.properties").getPath();
//通过getResource 获得该类的URL,在通过getPath方法获得String路径
FileInputStream fi = new FileInputStream(path);//读取文件
Properties props = new Properties();
props.load(fi);
Enumeration<Object> keys = props.keys();
while(keys.hasMoreElements()){
String key = (String) keys.nextElement();
System.out.println(key +"="+ props.getProperty(key));
}
System.out.println("==================");
//2.通过类装载器获得类所在的目录this.getClass().getClassLoader().getResourceAsStream(当前目录);
InputStream in = this.getClass().getClassLoader().getResourceAsStream("db.properties");
//如果该文件信息发送修改,则不能及时更正,因为通过本类的类加载器加载进来的信息,如果加载的文件已经加载过,则不用重新加载
Properties props2 = new Properties();//修改该文件后,将不能及时显示更新后 信息
props2.load(in);
Enumeration<Object> keys2 = props2.keys();
while(keys2.hasMoreElements()){
String key = (String) keys2.nextElement();
System.out.println(key +"="+ props2.getProperty(key));
}
}
}