温馨提示×

java properties类怎么使用

小亿
83
2023-09-20 16:10:28
栏目: 编程语言

在Java中,可以通过Properties类来读取和写入属性文件。下面是Properties类的使用示例:

  1. 创建Properties对象并加载属性文件:
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
  1. 读取属性值:
String value = properties.getProperty("key");
System.out.println(value);
  1. 设置属性值:
properties.setProperty("key", "value");
  1. 保存属性文件:
try {
FileOutputStream fileOutputStream = new FileOutputStream("config.properties");
properties.store(fileOutputStream, "Config Properties");
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

以上就是使用Properties类读取和写入属性文件的基本步骤。需要注意的是,属性文件的格式为键值对,如"key=value",每个属性占一行。

0