Java读取properties配置文件

Java读取properties配置文件

[java]  view plain copy print ?
  1. import java.io.FileInputStream;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.IOException;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7. import java.util.Properties;  
  8.   
  9. public class Property {  
  10.       
  11.     private static Map<String, String> propertyMap = new HashMap<String, String>();  
  12.   
  13.     private String fileName;  
  14.       
  15.     public Property(String fileName) {  
  16.         this.fileName = fileName;  
  17.     }  
  18.       
  19.     public String getProperty(String key) throws FileNotFoundException, IOException {  
  20.         String value = Property.propertyMap.get(key);  
  21.         Properties property = new Properties();  
  22.         FileInputStream inputFile = null;  
  23.           
  24.         if (value == null) {  
  25.             // 实例化inputFile,如config.properties文件的位置  
  26.             inputFile = new FileInputStream(this.fileName);  
  27.             // 装载配置文件  
  28.             property.load(inputFile);  
  29.               
  30.             value = property.getProperty(key);  
  31.             Property.propertyMap.put(key, value);  
  32.         }  
  33.         return value;  
  34.     }  
  35.       
  36.     public Map<String,String> getProperty(List<String> propertyList) throws FileNotFoundException, IOException {  
  37.         // 定义Map用于存放结果  
  38.         Map<String,String> propertyMap = new HashMap<String,String>();  
  39.         // 定义Properties property = new Properties();  
  40.         Properties property = new Properties();  
  41.         // 定义FileInputStream inputFile = null;    
  42.         FileInputStream inputFile = null;  
  43.           
  44.         try {  
  45.             // 实例化inputFile  
  46.             inputFile = new FileInputStream(this.fileName);  
  47.             // 装载配置文件  
  48.             property.load(inputFile);  
  49.             for (String name : propertyList) {  
  50.                 // 从配置文件中获取属性存入map中  
  51.                 String data = property.getProperty(name);  
  52.                 propertyMap.put(name, data);  
  53.             }  
  54.           
  55.         } finally {  
  56.             // 关闭输入流  
  57.             if (inputFile != null) {  
  58.                 inputFile.close();  
  59.             }  
  60.         }  
  61.           
  62.         return propertyMap;  
  63.     }  
  64. }  


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值