基于java如何读取并引用自定义配置文件?

这篇文章将为大家详细讲解有关基于java如何读取并引用自定义配置文件?,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

首先在resources目录创建自定义的配置文件

基于java如何读取并引用自定义配置文件?

配置文件的格式:

基于java如何读取并引用自定义配置文件?

写工具类,得到配置参数

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

public class MyConfig {
  public static Properties myProp = new Properties();
  public static InputStream myResource = MyConfig.class.getResourceAsStream("/myConfig.properties");
  static {
    try {
      myProp.load(myResource);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public String getMyConf(String props) {
    return myProp.getProperty(props);
  }
  
  public static void main(String[] args) {
    final MyConfig myConfig = new MyConfig();
    System.out.println(myConfig.getMyConf("master_ip"));
  }
}

关于基于java如何读取并引用自定义配置文件?就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。