属性对象包含键和值对作为字符串。
java.util.properties类是Hashtable的子类。
它可用于基于属性密钥获取属性值。
属性类提供从属性文件中获取数据并将数据存储到属性文件中的方法。
此外,它可用于获得系统的属性。
加载属性
要加载与应用程序捆绑的属性文件:
public class Defaults {
public static Properties loadDefaults() {
try (InputStream bundledResource =
Defaults.class.getResourceAsStream("defaults.properties")) {
Properties defaults = new Properties();
defaults.load(bundledResource);
return defaults;
} catch (IOException e) {
throw new UncheckedIOException(
"defaults.properties not properly packaged"
+" with application", e);
}
}
}
如何将Java属性保存为XML
将属性文件存储为XML文件的方式与将它们存储为.properties文件的方式非常相似。只需使用storeToXML()而不是store()。
public void saveProperties(String location) throws IOException{
//创建属性的新实例
Properties prop = new Properties();
//设置属性值
prop.setProperty("name", "Steve");
prop.setProperty("color", "green");
prop.setProperty("age", "23");
//检查文件是否已存在
File file = new File(location);
if (!file.exists()){
file.createNewFile();
}
//保存属性
prop.storeToXML(new FileOutputStream(file), "testing properties with xml");
}
从XML文件加载Java属性
现在要将此文件作为属性加载,需要调用loadFromXML()而不是常规.properties文件使用的load()。
public static void loadProperties(String location) throws FileNotFoundException, IOException{
//创建新的属性实例以将文件载入
Properties prop = new Properties();
//检查文件是否存在
File file = new File(location);
if (file.exists()){
//加载文件
prop.loadFromXML(new FileInputStream(file));
//打印出所有的属性
for (String name : prop.stringPropertyNames()){
System.out.println(name + "=" + prop.getProperty(name));
}
} else {
System.err.println("Error: No file found at: " + location);
}
}
运行此代码时,我们将在控制台中获取以下内容:
age=23 color=green name=Steve
日期:2020-06-02 22:15:24 来源:oir作者:oir
