java怎么读取config目录下配置文件

   2025-02-21 6100
核心提示:要读取config目录下的配置文件,可以使用Java中的Properties类来实现。首先,需要通过类加载器获取到配置文件的输入流。假设配置

要读取config目录下的配置文件,可以使用Java中的Properties类来实现。

首先,需要通过类加载器获取到配置文件的输入流。假设配置文件的名字是config.properties,可以使用以下代码获取到输入流:

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");

接下来,可以使用Properties类加载输入流,并读取配置文件中的内容:

Properties properties = new Properties();properties.load(inputStream);

现在,配置文件中的内容已经加载到Properties对象中了。可以通过getProperty()方法来获取配置项的值:

String configValue = properties.getProperty("config.key");

其中,config.key是配置项的键值。

完整的代码示例:

import java.io.InputStream;import java.util.Properties;public class ConfigReader {public static void main(String[] args) {try {// 获取配置文件的输入流InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");// 加载配置文件Properties properties = new Properties();properties.load(inputStream);// 读取配置项的值String configValue = properties.getProperty("config.key");System.out.println("配置项的值是:" + configValue);// 关闭输入流inputStream.close();} catch (Exception e) {e.printStackTrace();}}}

请确保配置文件config.properties位于config目录下,并且在类路径中可访问到。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言