java web项目中读取配置文件

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

方式一、在servlet中读取:

1
2
3
4
5
6
7
8
9
10
// action配置文件路径 
public  static  final  String ACTIONPATH =  "WEB-INF/classes/actions.properties"
// 属性文件  
public  static  final  Properties prop =  new  Properties(); 
// 获取servlet上下文的绝对路径,如:C:Program FilesApacheTomcat 6.0webappsfee 
String path = getServletContext().getRealPath("\");    
// 把文件读入文件输入流,存入内存中    
FileInputStream fis =  new  FileInputStream( new  File(path + ACTIONPATH));    
//加载文件流的属性    
prop.load(fis);

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

1
2
3
4
5
6
7
8
9
10
// 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);

读取文件的属性的值:

1
2
String propertyName =  "aa"
String propertyValue = prop.getProperty(propertyName );
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值