0

My code:

public static InputStream input = null;
public static Properties prop = new Properties();

static public void getConstants(){ 
    Constants constants = new ConstantsEng();
    try {

        input = CLASS_NAME.class.getClassLoader().getResourceAsStream("FILE_NAME.properties");

        prop.load(input);
    } catch (IOException e) {
        e.printStackTrace();
    }

public static String SOURCE = prop.getProperty("SOURCE");
public static String SOURCES = prop.getProperty("SOURCES");
public static String DESTINATION = prop.getProperty("DESTINATION");
public static String DESTINATIONS = prop.getProperty("DESTINATIONS");

FILE_NAME.properties

SOURCE=Source
SOURCES=${SOURCE}s
DESTINATION=Destination
DESTINATIONS=${DESTINATION}s

The strings display with the placeholders in when rendered:

Output

I want to reuse strings in my .properties file but this code doesn't work. Is there any way round it, or am I making a mistake?

When I fetch:

public static String SOURCES = prop.getProperty("SOURCES");

I'm expecting "Sources" as output.

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
Rakesh
  • 45
  • 1
  • 9

2 Answers2

0

You can use "%s" in your properties file for String composition:

SOURCE=Source
SOURCES=%ss

Then, you would have to format the String:

public static String SOURCES = String.format(prop.getProperty("SOURCES"), prop.getProperty("SOURCE"));
Eduardo
  • 319
  • 2
  • 14
0

Have you considered using Apache's commons-configuration?

Dependency to add in pom.xml

<dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>1.6</version>
</dependency>

Your class will be like

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

public class Configurations {
    private CompositeConfiguration config;

    public void getConstants() throws ConfigurationException {
        config = new CompositeConfiguration();
        config.addConfiguration(new PropertiesConfiguration("test.properties"));
    }

    public CompositeConfiguration getConfig() {
        return config;
    }

    public static void main(String... args) throws ConfigurationException {
        Configurations config = new Configurations();
        config.getConstants();

        System.out.println(config.getConfig().getString("SOURCE"));
        System.out.println(config.getConfig().getString("SOURCES"));
    }
}

test.properties

SOURCE=Source
SOURCES=${SOURCE}s
DESTINATION=Destination
DESTINATIONS=${DESTINATION}s
Prasann
  • 1,263
  • 2
  • 11
  • 18