我可以在Java中使用哪种方法来配置文件?

时间:2016-10-24 12:30:55

标签: java configuration configuration-files

我可以在Java中使用哪种方法来配置文件,读写特定的行和字符串?例如(config.ini):

mysql_host: localhost
mysql_user: user

mysql_host = localhost
mysql_user = user

2 个答案:

答案 0 :(得分:0)

查看Java Properties

  

属性是作为键/值对管理的配置值。在   每对,键和值都是字符串值。钥匙   标识,并用于检索值,就像变量一样   name用于检索变量的值。例如,一个   能够下载文件的应用程序可能使用名为的属性   " download.lastDirectory"跟踪用于的目录   上次下载。

     

要管理属性,请创建java.util.Properties的实例。这个   class提供以下方法:

     
      
  • 将键/值对从流中加载到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---");
}

答案 1 :(得分:0)

您可以使用ini4j库。

Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);

然后您可以继续使用prefs.node("mysql_host")获取节点。

相关问题