欢迎来到之路教程(on itroad-com)
示例: Java 程序在属性文件中写入新的键值对
因此,如果我们面临类似的情况,请在“PropertiesCache.java”中再创建两个方法,如下所示:
public void setProperty(String key, String value){ configProp.setProperty(key, value); } public void flush() throws FileNotFoundException, IOException { try (final OutputStream outputstream = new FileOutputStream("application.properties");) { configProp.store(outputstream,"File Updated"); outputstream.close(); } }
- 使用
setProperty(k, v)
方法将新属性写入属性文件。 - 使用
flush()
方法将更新的属性写回到application.properties
文件中。
PropertiesCache cache = PropertiesCache.getInstance(); if(cache.containsKey("country") == false){ cache.setProperty("country", "Netherlands"); } // 查看新属性 System.out.println(cache.getProperty("country")); // 写入到文件 PropertiesCache.getInstance().flush();
日期:2020-09-17 00:09:29 来源:oir作者:oir