Java - 属性:在运行时向属性文件添加新键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7571045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Properties: Add new keys to properties file in run time?
提问by Olcay Erta?
Is it possible to create a new properties file and add keys and values in run time? I want to add new keys to properties file depending on user input while installing my application. I checked out Java Properties class but it seem it can set values to existing keys but can not add new keys to properties file.
是否可以在运行时创建新的属性文件并添加键和值?我想在安装我的应用程序时根据用户输入向属性文件添加新密钥。我检查了 Java Properties 类,但它似乎可以为现有键设置值,但不能向属性文件添加新键。
回答by Jon Skeet
You can add new properties just by calling setProperty
with a key which doesn't currently exist. That will only do it in memory though - you'll have to call store
again to reflect the changes back to a file:
您可以通过setProperty
使用当前不存在的键调用来添加新属性。但这只会在内存中执行 - 您必须store
再次调用以将更改反映回文件:
Properties prop = new Properties();
prop.load(...); // FileInputStream or whatever
prop.setProperty("newKey", "newValue");
prop.store(...); // FileOutputStream or whatever