Java读取properties配置文件


Java读取properties配置文件

  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. }  

相关内容