Linux教程網
- package com.justsy;
-
- import java.io.InputStream;
- import java.util.Properties;
-
- public class PropertiesManager {
-
- private String resName = "appstore.properties";
-
- private Properties prop = new Properties();
-
- public PropertiesManager configuration() {
-
- try {
- InputStream is = PropertiesManager.class.getClassLoader()
- .getResourceAsStream(resName);
- prop.load(is);
- if (is != null)
- is.close();
- } catch (Exception e) {
- System.out.println(e + "file " + resName + " not found");
- }
- return this;
- }
-
- public String getPara(String url) {
- return prop.getProperty(url);
- }
-
- public static void main(String[] args) {
- PropertiesManager pm = new PropertiesManager().configuration() ;
-
- System.out.println(pm.getPara("url"));
- }
-
- }
使用單例進行優化後的工具類
[java]
- package com.justsy.eas.util;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
-
- import org.apache.log4j.Logger;
- /**
- * 讀取配置文件
- */
- public class PropertiesReader {
- private Logger logger = Logger.getLogger(Properties.class) ;
- private Properties properties ;
- private static PropertiesReader propertiesReader = new PropertiesReader() ;
-
- private String resName = "eas.properties" ;
-
- // 單例私有化構造方法
- private PropertiesReader(){
- InputStream is = PropertiesReader.class.getClassLoader()
- .getResourceAsStream(resName);
- properties = new Properties() ;
- try {
- properties.load(is);
- logger.info("加載配置信息!!") ;
- } catch (IOException e) {
- logger.warn("加載配置文件出錯!") ;
- //e.printStackTrace();
- }
- }
-
- // 得到PropertiesReader的實例
- public static PropertiesReader getInstance(){
- if(propertiesReader==null){
- return new PropertiesReader() ;
- }
- return propertiesReader ;
- }
-
- // 返回所有屬性
- public Properties getProperties(){
- return this.properties ;
- }
-
- public static void main(String[] args) {
- Properties properties = PropertiesReader.getInstance().getProperties() ;
- System.out.println(properties.getProperty("dbaddr"));
- }
-
- }
Copyright ©
Linux教程網 All Rights Reserved