如何用Java读取并引用自定义配置文件?

2026-05-24 07:231阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计234个文字,预计阅读时间需要1分钟。

如何用Java读取并引用自定义配置文件?

首先在resources目录下创建自定义的配置文件+配置文件的格式为:+编写工具类,获取配置参数+import java.io.IOException;+import java.io.InputStream;+import java.util.Properties;+public class MyConfig {+public static Properties loadConfig() throws IOException {+ InputStream is=null;+ try {+ is=MyConfig.class.getClassLoader().getResourceAsStream(config.properties);+ Properties properties=new Properties();+ properties.load(is);+ return properties;+ } finally {+ if (is !=null) {+ is.close();+ }+ }+}+}+使用示例:+Properties props=MyConfig.loadConfig();+String value=props.getProperty(key);+System.out.println(value);+}

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

配置文件的格式:

如何用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")); } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计234个文字,预计阅读时间需要1分钟。

如何用Java读取并引用自定义配置文件?

首先在resources目录下创建自定义的配置文件+配置文件的格式为:+编写工具类,获取配置参数+import java.io.IOException;+import java.io.InputStream;+import java.util.Properties;+public class MyConfig {+public static Properties loadConfig() throws IOException {+ InputStream is=null;+ try {+ is=MyConfig.class.getClassLoader().getResourceAsStream(config.properties);+ Properties properties=new Properties();+ properties.load(is);+ return properties;+ } finally {+ if (is !=null) {+ is.close();+ }+ }+}+}+使用示例:+Properties props=MyConfig.loadConfig();+String value=props.getProperty(key);+System.out.println(value);+}

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

配置文件的格式:

如何用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")); } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。