【问题标题】:Using properties file in Java: copy key value and assign it to another key在 Java 中使用属性文件:复制键值并将其分配给另一个键
【发布时间】:2022-09-23 23:52:54
【问题描述】:

是否可以使用 Java 中的属性文件来实现以下场景。非常感谢您的任何反馈。

假设我有一个 settings.properties 文件,其中包括,

my.name=${name}
his.name=hisNameIs${name}

在我的代码中,

InputStream input = new FileInputStream(\"path/settings.properties\");
Properties prop = new Properties();
prop.setProperty(\"my.name\", \"John\");
prop.load(input);
String output=  prop.getProperty(his.name);
System.out.println(output);

预期成绩:

hisNameIsJohn

标签: java


【解决方案1】:

Apache Commons Configuration 项目有一个能够进行变量插值的实现。

阅读名为变量插值的部分

application.name = Killer App
application.version = 1.6.2
application.title = ${application.name} ${application.version}

你会在你的类路径中需要这个第三方库,但另一方面,你不必担心为此编写另一个实现:)

您可能还想阅读Properties How To

【讨论】:

  • 非常感谢,能够使用 org.apache.commons.configuration.PropertiesConfiguration 解决这个问题
【解决方案2】:

使用org.apache.commons.configuration.PropertiesConfiguration 发布解决方案

PropertiesConfiguration prop = new PropertiesConfiguration(new File("path/settings.properties"));
    prop.addProperty("name", "John");
    prop.getProperty(his.name);

在“settings.properties”文件中。

his.name=hisNameIs${name}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多