【发布时间】:2016-10-24 12:30:55
【问题描述】:
我可以在 Java 中对配置文件使用哪种方法来读取和写入特定的行和字符串?例如(config.ini):
mysql_host: localhost
mysql_user: user
或
mysql_host = localhost
mysql_user = user
【问题讨论】:
标签: java configuration configuration-files
我可以在 Java 中对配置文件使用哪种方法来读取和写入特定的行和字符串?例如(config.ini):
mysql_host: localhost
mysql_user: user
或
mysql_host = localhost
mysql_user = user
【问题讨论】:
标签: java configuration configuration-files
您可以使用ini4j 库。
Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
然后您可以使用prefs.node("mysql_host") 继续获取节点。
【讨论】:
属性是作为键/值对管理的配置值。在 每对,键和值都是字符串值。钥匙 识别并用于检索值,就像变量一样 name 用于检索变量的值。例如,一个 能够下载文件的应用程序可能会使用一个名为 "download.lastDirectory" 用于跟踪用于 最后一次下载。
要管理属性,请创建 java.util.Properties 的实例。这个 类提供以下方法:
- 将键/值对从流中加载到 Properties 对象中,
- 从其键中检索一个值,
- 列出键及其值,
- 枚举键,
- 并将属性保存到流中。
您可以使用
加载属性文件Properties applicationProps = new Properties();
try (FileInputStream in = new FileInputStream("appProperties")) {
applicationProps.load(in);
}
并将它们存储在
try (FileOutputStream out = new FileOutputStream("appProperties")) {
applicationProps.store(out, "---No Comment---");
}
【讨论】: