Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use place holders in Apache PropertiesConfiguration

I have the following configuration setup using Apache Configuration:

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

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

I want to know if there is some way to use place holders in the properties file? For example, I want to have this:

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

And be able to pass in the value for the {0} place holder. Typically, you can usually do something like config.getString("some.message", String[] of values) but don't see anything like that.

like image 662
Ascalonian Avatar asked Sep 08 '25 15:09

Ascalonian


1 Answers

As far as I know, Configuration class doesn't provide any formatters. So, for your task

  1. You can use MessageFormat as it was suggested by Bilguun. Please note, that format method is static.

  2. You can use String.format function.

Examples is bellow:

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}!

Example class

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"));
    }
}
like image 197
Solorad Avatar answered Sep 10 '25 04:09

Solorad