爱编程的欧巴

让我们成长吧~
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

读取Config文件工具类 PropertiesConfig.java

Posted on 2016-01-29 13:28  爱编程的欧巴  阅读(598)  评论(0编辑  收藏  举报
  1. package com.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.FileInputStream;  
  5. import java.io.InputStream;  
  6. import java.util.Properties;  
  7. /** 
  8.  * 读取Config文件工具类 
  9.  * @version 1.0 
  10.  * @since JDK 1.6 
  11.  */  
  12. public class PropertiesConfig {    
  13.         
  14.     /**  
  15.      * 获取整个配置文件中的属性 
  16.      * @param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties  
  17.      */    
  18.     public static Properties readData(String filePath) {    
  19.         filePath = getRealPath(filePath);  
  20.         Properties props = new Properties();    
  21.         try {    
  22.             InputStream in = new BufferedInputStream(new FileInputStream(filePath));    
  23.             props.load(in);    
  24.             in.close();    
  25.             return props;    
  26.         } catch (Exception e) {    
  27.             e.printStackTrace();    
  28.             return null;    
  29.         }    
  30.     }    
  31.       
  32.     private static String getRealPath(String filePath) {  
  33.         //获取绝对路径 并截掉路径的”file:/“前缀    
  34.         return PropertiesConfig.class.getResource("/" + filePath).toString().substring(6);  
  35.     }