Java中如何读取配置文件中的键值对

答案是使用Properties类读取.properties配置文件。通过创建config.properties文件并将其放入资源目录,利用ClassLoader加载输入流,用Properties的load()方法解析内容,再通过getProperty()获取键值,支持默认值设置,可遍历或检查键存在性,需处理IO异常以保证程序健壮性。

在Java中读取配置文件中的键值对,最常见的方式是使用.properties文件配合java.util.Properties类。这种方式简单、高效,适用于大多数应用场景。

1. 创建properties配置文件

在项目资源目录(如src/main/resources)下创建一个文本文件,例如config.properties

app.name=MyApplication
app.version=1.0.0
database.url=jdbc:mysql://localhost:3306/mydb
database.username=root
database.password=secret

2. 使用Properties类加载配置

通过Properties对象的load()方法读取文件内容:

Properties props = new Properties();
try (InputStream input = getClass().getClassLoader()
  .getResourceAsStream("config.properties")) {
  if (input == null) {
    System.out.println("无法找到配置文件");
    return;
  }
  props.load(input);
} catch (IOException ex) {
  ex.printStackTrace();
}

3. 获取键值对

使用getProperty()方法获取指定键的值:

String appName = props.getProperty("app.name");
String dbUrl = props.getProperty("database.url");

System.out.println("应用名称:" + appName);
System.out.println("数据库地址:" + dbUrl);

也可以设置默认值:

String timeout = props.getProperty("app.timeout", "30");

4. 其他实用操作

遍历所有键值对:

props.forEach((key, value) ->
  System.out.println(key + " = " + value));

检查某个键是否存在:

if (props.containsKey("database.username")) {
  String user = props.getProperty("database.username");
}

基本上

就这些。只要配置文件放在类路径下,用ClassLoader加载即可。注意处理文件不存在或IO异常的情况,确保程序健壮性。