JAVA实现读取自定义配置文件.properties的两种方法

JAVA实现读取自定义配置文件.properties的两种方法

如下图:
在这里插入图片描述
要获取resource下面自定义的配置文件,可使用下面的两种方法(要放在resource下面才能读取得到)

一、用getResourceAsStream(filePath)获取

这个项目上经常用到,主要是用到getClass().getResourceAsStream(filePath)来获取到文件流,然后将流加载入Properties,然后再读取,上代码:

Properties p = new Properties();
  //获取文件的流
  InputStream inStream = this.getClass().getResourceAsStream("/mini.properties");
  if(inStream == null){
   try {
    throw new Exception("can not find file!");
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  try {
   p.load(inStream);
   appId = p.getProperty("mini.appId");
   if(!StringUtils.isEmpty(appId)){appId = appId.trim();}
   System.out.println(appId);
   appSecret = p.getProperty("mini.appSecret");
   if(!StringUtils.isEmpty(appSecret)){appSecret = appSecret.trim();}
   System.out.println(appSecret);
  } catch (IOException e) {
   try {
    throw new Exception("load mini.properties fail!");
   } catch (Exception e1) {
    e1.printStackTrace();
   }
  }
  System.out.println("load mini.properties success!");

我这里是用在SpringBoot启动的时候用@Configuration加载配置,把上面的代码放在构造函数里面,然后设计成单例模式。其实用什么方法加载不重要,重要的是能获取到配置文件的内容。运行完后出来的结果:
在这里插入图片描述

二、用ResourceBundle.getBundle(fileName)获取

这个要注意的是filename是不带后缀的,上代码

ResourceBundle resource = ResourceBundle.getBundle("mini");
  try {
   String appId = new String(resource.getString("mini.appId")
     .trim()
     .getBytes("ISO-8859-1"), "utf-8");//防止乱码
   System.out.println(appId);
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }

我这个是在main里面运行的,运行结果:
在这里插入图片描述

这两种方式,都可以获取得到自定义的配置文件,看你怎么选择了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值