java读取资源文件代码

package com.huawei.pms.realtime.util;

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

import org.apache.log4j.Logger;

/**
 * 
 * 用于处理 properties 文件,从中获得配置信息
 * 
 * PropertiesOperator
 * @author fhuan123
 * 2009-7-6上午09:03:50
 * @phone 13733836515
 */
public class PropertiesOperator
{
    private static Logger logger = Logger.getLogger(PropertiesOperator.class
            .getName());

    /**
     *  @describe 从固定的配置文件中,根据指定的 key 来查找对应的属性
     *  
     *  @param key 对应的键
     *  
     */
    public static String getValueByKey(String key)
    {
        String result = null;
        Properties p = new Properties();

        InputStream in = PropertiesOperator.class.getClassLoader()
                .getResourceAsStream("config.properties");

        try
        {
            p.load(in);
            result = p.getProperty(key);
        }
        catch (IOException e)
        {
            logger.debug("check host --- load properties happend err");
            e.printStackTrace();
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (Exception e)
            {
                logger.error(e) ;
            }
        }

        return result;
    }

    /**
     *  @describe 根据指定的配置文件名和Key 返回 key 的属性值
     *  @param name 配置文件名
     *  @param key 键
     *  @return 返回 属性值
     */
    public static String getValueByKey(String name, String key)
    {
        String result = null;
        Properties p = new Properties();

        InputStream in = PropertiesOperator.class.getClassLoader()
                .getResourceAsStream(name);

        try
        {
            p.load(in);
            result = p.getProperty(key);
        }
        catch (IOException e)
        {
            logger.debug("check host --- load properties happend err");
            e.printStackTrace();
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (Exception e)
            {
                logger.error(e) ;
            }
        }

        return result;
    }

    public static void main(String[] args)
    {
        // System.out.println(getValueByKey("INFO_FILE_PATH")) ;
        // System.out.println(getValueByKey("masterIp")) ;
        // System.out.println(getValueByKey("masterPort")) ;
        // System.out.println(getValueByKey("configservice.properties","hostName")) ;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值