用java读取解析一个含有变量的配置文件

该博客展示了一段Java代码,用于读取并解析配置文件。通过`getProperties`方法读取文件,将配置文件的键值封装在`Properties`对象中,若值包含`${}`,会将其中变量替换为对应值,最后在`main`方法中测试并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.*;
import java.io.*;

public final class ConfigurationFile{
  private ConfigurationFile(){}
  /*读取解析配置文件
   *param:fileName:配置文件名
   */
  protected static Properties getProperties(String fileName){
    Properties props = new Properties();
    try{
      FileInputStream fis = new FileInputStream(fileName);
      props.load(fis);
      //System.out.println(props.size());
    }catch(Exception e){
      e.printStackTrace();
    }
    //props.propertyNames()将配置文件的key封装在一个Enumeration对象中
    Enumeration et = props.propertyNames();
    //依次解析每一个key对应的value
    while(et.hasMoreElements()){
      String ekey = (String)et.nextElement();
      String evalue = props.getProperty(ekey);
      //如果value中包含${,则将${}中的变量替换成变量对应的值
      if(evalue.indexOf("${") != -1){
        Iterator it = props.keySet().iterator();
        while(it.hasNext()){
          String k = (String)it.next();
          String v = props.getProperty(k);
          evalue = evalue.replaceAll("[$]//{"+k+"
//}",v);
        }
      }   
      props.put(ekey,evalue);
    }
    return props;
  }
  
  //-------测试打印------
  public static void main(String[] args){
    Properties prop = getProperties("mytest.properties");
    //System.out.println(prop.getProperty("name"));
    Iterator it = prop.keySet().iterator();
    while(it.hasNext()){
      String k = (String)it.next();
      String v = prop.getProperty(k);
      System.out.println(k + ":" + v);
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值