读配置文件properties

来源:互联网 发布:房屋租赁软件 编辑:程序博客网 时间:2024/06/06 00:44

package com.sais.inkaNet.common.util;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;


public class PropertiesUtil {
    private static final Logger log = Logger.getLogger(PropertiesUtil.class);

  /*
   * 参数设置
   */
  private static Properties settings = null;
  private static InputStream is = null;
  private static URL url = null;
  static {
   // 读取属性文件,并将参数存入变量
    is = PropertiesUtil.class.getResourceAsStream("/config/ftp.properties");
    url = ClassLoader.getSystemResource("config/ftp.properties");
   settings = new Properties();
   try {
    settings.load(is);
    log.info("读取ftp配置文件完成");
   } catch (Exception e) {
    //System.err.println("不能读取属性文件. ");
    log.error("读取ftp配置信息失败!\n"+e.getMessage());
   }
  }
  
  
  /**
   *
   * @title:    getSetting
   * @描述:      获得properties设置的属性信息
   *
   * @param key properties key
   * @param defaultValue 如果key值不存在或key对应的value为空,则取defaultValue
   * @return:   String
   */
  public static String getSetting(String key, String defaultValue) {
   return settings.getProperty(key, defaultValue);
  }
  /**
   *
   * @title:    setSetting
   * @描述:      创建新的属性信息
   *
   * @param key 要更新或要添加新属性的key
   * @param value key对应的value
   * @return:   void
      */
  public static void setSetting(String key,String value){
          log.info("LOG:PropertiesUtil getSettings");
          OutputStream fos = null;
    try {
     fos = new BufferedOutputStream(new FileOutputStream(url.getPath()));
     settings.setProperty(key, value);
     settings.store(fos, "Update "+key);
     fos.close();
     is.close();
    } catch (IOException e) {
     log.error(e.getMessage());
     e.printStackTrace();
    }finally{
      try {
       if(fos !=null){
        fos.close();
       }
       if(is != null){
        is.close();
       }
      } catch (IOException e) {
       e.printStackTrace();
      }
     
    }
    
  }
}

 

得到你properties中属性名为inkanetmis.appfolder的值

String appfolder = PropertiesUtil.getSetting(
     "inkanetmis.appfolder", "");

原创粉丝点击