java - 有没有办法在 Apache PropertiesConfiguration 中使用占位符

标签 java properties apache-config

我使用 Apache 配置设置了以下配置:

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;

Configuration config = new PropertiesConfiguration("config.properties");

我想知道是否有一些方法可以在属性文件中使用占位符?例如,我想要这个:

some.message = You got a message: {0}

并且能够传入 {0} 占位符的值。通常,您通常可以执行类似 config.getString("some.message", String[] of values) 的操作,但看不到类似的内容。

最佳答案

据我所知,配置类不提供任何格式化程序。所以,为了你的任务

  1. 您可以按照 Bilguun 的建议使用 MessageFormat。请 请注意,该格式化方法是静态

  2. 您可以使用String.format 函数。

示例如下:

config.properties

enter some.message.printf=%1$s\, you've got a message from %2$s \n
some.message.point.numbers =Hey {0}\, you got message: {1}!

示例类

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.text.MessageFormat;

public class ConfigurationTest {


    public static void main(String[] args) throws ConfigurationException {
        Configuration config = new PropertiesConfiguration("config.properties");

        String stringFormat = String.format(config.getString("some.message.printf"), "Thomas", "Andrew");
        // 1 String format
        System.out.println(stringFormat);
        // 2 Message Format
        System.out.println(MessageFormat.format(config.getString("some.message.point.numbers"), "Thomas", "Hello"));
    }
}

关于java - 有没有办法在 Apache PropertiesConfiguration 中使用占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35351181/

相关文章:

apache - 为 Google 抓取提供的不同页面

php - 自定义 php.ini/php_value : which takes precedence?

java - Spring MVC 依赖注入(inject)理解

java - 在 wicket 有没有办法直接读取本地化属性?

html - 停止 CSS 背景属性在调整大小时移动背景

WordPress 和 SEO : how to mask a path/pull content from another domain

java - Android Javascript 接口(interface)失败

java - 包含所有 Drawable 的 Android Studio 对话框

java - 使用 XSLT 打印 XML 元素内的一组键值对数据

c# - PropertyInfo.GetValue(myObject, null).GetType() 返回 "Object reference not set to an instance of an object."