ResourceBundle轻松读取properties配置文件

在工作中经常遇到将参数放到配置文件中动态读取进来的情况,下面介绍一下通过ResourceBundle读取properties的方法。
ResourceBundle是资源包包含特定于语言环境的对象。当程序需要一个特定于语言环境的资源时(如 String),程序可以从适合当前用户语言环境的资源包中加载它。使用这种方式,可以编写很大程度上独立于用户语言环境的程序代码,它将资源包中大部分(即便不是全部)特定于语言环境的信息隔离开来。

上代码:

public class ResourceUtil {
public static final Logger log = Logger.getLogger(ResourceUtil.class);
private static ResourceBundle systemProperties;
//配置文件myConfig.properties放在classpath下面otherConfigs目录下面
public static final String PROPERTIES_FILE_NAME = "otherConfigs.myConfig";
//通过静态块加载 ResourceBundle 类
static{
try{
systemProperties = ResourceBundle.getBundle(PROPERTIES_FILE_NAME,Locale.ENGLISH);
}catch(Exception e){
log.error(e);
}
}

public static int getPropertyByName(String name) {
String str=systemProperties.getString(name);
return str;
}
}

假定配置文件myConfig.properties的内容如下:

test = 3
str= 4

通过ResourceUtil.getPropertyByName("test")即可读取到键为“test”的值:3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值