java 读取properties文件

在实际开发工作中,我们又是会将一些路径文件配置放在properties文件中,这样我们需要修改路径的时候就只需要写该一下配置文件就行了,不需要在代码中挨个挨个的去改。但是我们怎样获得配置文件中的值呢?其实这个很简单,我们只需要封装如下一个工具类就行了:

public class UrlUtil {
    private static Properties config = null;

     static {
          InputStream in = UrlUtil.class.getClassLoader().getResourceAsStream("url.properties");
          config = new Properties();     
           try {
            config.load(in);
            in.close();
          } catch (IOException e) {
            //读取url.properties出错
            e.printStackTrace();
         }  
     }
     
      /**
       * 通过键获得对应的值
       * @param key
       * @return
       */
     public static String getValue(String key) {
      try {
       String value = config.getProperty(key);
       return value.trim();
      } catch (Exception e) {
       e.printStackTrace(); 
       return null;
      }
     }

     /**
      * 读取properties的全部信息*/
     public static void getAllProperties() {
      try {
       Enumeration en = config.propertyNames();
       while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        String Property = config.getProperty(key);
       }
      } catch (Exception e) {
        e.printStackTrace();
        System.err.println("ConfigInfoError" + e.toString());
      }
     }
     public static void main(String args[]) {
      
     }
}

代码中的url.properties就是我们放置路径的配置文件。比如我们的url.properties中有个图片路径:imgPath=c:/images

我们要取得这个值只需要使用:UrlUtil.getValue("imgPath")就行了。

转载于:https://www.cnblogs.com/mouseIT/p/4193982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值