Java中读取资源文件的工具类


  1. package com.justsy;  
  2.   
  3. import java.io.InputStream;  
  4. import java.util.Properties;  
  5.   
  6. public class PropertiesManager {  
  7.   
  8.     private String resName = "appstore.properties";  
  9.   
  10.     private Properties prop = new Properties();  
  11.   
  12.     public PropertiesManager configuration() {  
  13.   
  14.         try {  
  15.             InputStream is = PropertiesManager.class.getClassLoader()  
  16.                     .getResourceAsStream(resName);  
  17.             prop.load(is);  
  18.             if (is != null)  
  19.                 is.close();  
  20.         } catch (Exception e) {  
  21.             System.out.println(e + "file " + resName + " not found");  
  22.         }  
  23.         return this;  
  24.     }  
  25.   
  26.     public String getPara(String url) {  
  27.         return prop.getProperty(url);  
  28.     }  
  29.       
  30.     public static void main(String[] args) {  
  31.         PropertiesManager pm = new PropertiesManager().configuration() ;  
  32.           
  33.         System.out.println(pm.getPara("url"));  
  34.     }  
  35.   
  36. }  

使用单例进行优化后的工具类

[java]

  1. package com.justsy.eas.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6.   
  7. import org.apache.log4j.Logger;  
  8. /** 
  9.  * 读取配置文件 
  10.  */  
  11. public class PropertiesReader {  
  12.     private Logger logger = Logger.getLogger(Properties.class) ;  
  13.     private Properties properties ;  
  14.     private static PropertiesReader propertiesReader = new PropertiesReader() ;  
  15.       
  16.     private String resName = "eas.properties" ;  
  17.       
  18.     // 单例私有化构造方法   
  19.     private PropertiesReader(){  
  20.         InputStream is = PropertiesReader.class.getClassLoader()  
  21.                 .getResourceAsStream(resName);  
  22.         properties = new Properties() ;  
  23.         try {  
  24.             properties.load(is);  
  25.             logger.info("加载配置信息!!") ;  
  26.         } catch (IOException e) {  
  27.             logger.warn("加载配置文件出错!") ;  
  28.             //e.printStackTrace();   
  29.         }  
  30.     }  
  31.       
  32.     // 得到PropertiesReader的实例   
  33.     public static PropertiesReader getInstance(){  
  34.         if(propertiesReader==null){  
  35.             return new PropertiesReader() ;  
  36.         }  
  37.         return propertiesReader ;  
  38.     }  
  39.       
  40.     // 返回所有属性   
  41.     public Properties getProperties(){  
  42.         return this.properties ;  
  43.     }  
  44.       
  45.     public static void main(String[] args) {  
  46.         Properties properties = PropertiesReader.getInstance().getProperties() ;  
  47.         System.out.println(properties.getProperty("dbaddr"));  
  48.     }  
  49.       
  50. }  

相关内容