Java 读取配置文件方案

package com.hpli.demo;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 *  配置文件帮助类
 *
 * @author  hpli/025415
 * @version  [版本号, 2012-3-22]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class ConfigHelper
{
 // 定义默认读取文件对象
 private static String DEFAULT_CONFIG = "config.properties";

 // 定义properties
 private static Properties properties = null;

 static
 {
  load();
 }

 private ConfigHelper()
 {

 }

 /**
  * 读取对应配置文件业务
  */
 public static void load()
 {
  // 得到工程绝对路径D:\hpli\Workspace\HispaceTest\WebRoot\WEB-INF\classes
  // String path = this.getClass().getResource("/").getPath();

  // 定义字节流对象
  InputStream inStream = null;

  try
  {
   // 实列化对象
   properties = new Properties();

   // 读取指定文件
   inStream = ClassLoader.getSystemResourceAsStream(DEFAULT_CONFIG);

   // 读取内容
   properties.load(inStream);
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }
  finally
  {
   try
   {
    inStream.close();
   }
   catch (IOException e)
   {
    e.printStackTrace();
   }
  }
 }

 /**
  * 获取默认配置文件中的属性值 方法表述
  *
  * @param key键值
  * @return 配置文件属性值 String
  */
 public static String getConfigInfo(String key)
 {
  // 临时value值变量
  String configInfo = "";

  // 如果properties对象不为空且包含对应key值时,获取返回对应value值
  if (properties != null && properties.containsKey(key))
  {
   configInfo = properties.getProperty(key);
  }

  return configInfo;
 }

 /**
  * 读取指定配置文件数据
  *
  * @param keyProperties 指定配置文件名
  * @param key 获取的key值
  * @return key对应的value
  */
 public static String getConfigInfo(String keyProperties, String key)
 {
  // 临时value值变量
  String configInfo = "";

  // keyProperties不为空,读取指定配置文件信息
  if (null != keyProperties && !"".equals(keyProperties))
  {
   DEFAULT_CONFIG = keyProperties;

   load();
  }

  // 如果properties对象不为空且包含对应key值时,获取返回对应value值
  if (properties != null && properties.containsKey(key))
  {
   configInfo = properties.getProperty(key);
  }

  return configInfo;
 }

 /**
  * 重新讀取
  */
 public static void reload()
 {
  load();
 }

 /**
  * 测试
  *
  * @param args
  */
 public static void main(String[] args)
 {
  System.out.println("--- key-value01:" + ConfigHelper.getConfigInfo("isDebug"));

  System.out.println("--- key-value02:" + ConfigHelper.getConfigInfo("congfig02.properties", "isDebug"));
 }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值