📅  最后修改于: 2023-12-03 15:16:30.234000             🧑  作者: Mango
java.util.Properties
类是Java中用于处理属性文件的类,属性文件通常以.properties
作为文件扩展名。它可以读取、写入和操作属性文件中的键-值对。
public class Properties extends Hashtable<Object,Object>
该类继承了Hashtable
类,并且泛型已被设置为Object,Object
以适应任意的对象类型。
Properties props = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {
props.load(input);
}
String value = props.getProperty("key");
System.out.println(value);
该代码片段会读取config.properties
文件中的key
属性的值,并将其打印到控制台中。
Properties props = new Properties();
props.setProperty("key", "value");
try (OutputStream output = new FileOutputStream("config.properties")) {
props.store(output, "This is a comment");
}
该代码片段会将一个新的键-值对key=value
写入到属性文件中,并附上一行注释。注释仅在属性文件的头部出现。
Properties props = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {
props.load(input);
}
props.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
该代码片段会枚举config.properties
文件中的所有键-值对,并将其打印到控制台中。 forEach()
方法是一个Java 8的新特性。
Properties
类是Java中处理属性文件的标准类。它可以读取、写入和操作属性文件中的键-值对,并能轻松地集成到Java应用程序中。程序员只需熟练使用Properties
类,便可方便处理属性文件,是一个非常有用的工具。