servlet学习笔记2 读取配置文件

servlet在服务运行的时候(或第一次打开的时候)创建,然后调用init,在服务关闭的时候销毁,调用destroy。servlet在运行过程中只有一个实例,所以servlet是线程不安全的,在servlet中的只读属性最好设置为final。

 

下文转载自:http://haotw.iteye.com/blog/963425

在Java web项目中经常会用属性文件作为配置文件,而其一般放在src的根目录下,读取文件时一般会有以下两种情况:

方式一、在servlet中读取: 

// action配置文件路径
public static final String ACTIONPATH = "WEB-INF/classes/actions.properties";
// 属性文件 
public static final Properties prop = new Properties();
// 获取servlet上下文的绝对路径,如:C:\Program Files\Apache\Tomcat 6.0\webapps\fee\
String path = getServletContext().getRealPath("\\");   
// 把文件读入文件输入流,存入内存中   
FileInputStream fis = new FileInputStream(new File(path + ACTIONPATH));   
//加载文件流的属性   
prop.load(fis);   

 方式二、在一般的类中读取: 

// action配置文件路径
public static final String ACTIONPATH = "actions.properties";
// 属性文件 
public static final Properties prop = new Properties();
// 获取当前类加载的根目录,如:/C:/Program Files/Apache/Tomcat 6.0/webapps/fee/WEB-INF/classes/
String path = UriFilter.class.getClassLoader().getResource("").toURI().getPath();  
// 把文件读入文件输入流,存入内存中
FileInputStream fis = new FileInputStream(new File(path + ACTIONPATH));   
//加载文件流的属性   
prop.load(fis);   

 读取文件的属性的值:

String propertyName = "aa";
String propertyValue = prop.getProperty(propertyName );
posted @ 2014-04-18 17:06  phk52  阅读(561)  评论(0)    收藏  举报