[java] Better way to represent array in java properties file

I'm currently making a .properties file that needs to be loaded and transformed into an array. But there is a possibility of anywhere from 0-25 of each of the property keys to exist. I tried a few implementations but i'm just stuck at doing this cleanly. Anyone have any ideas?

foo.1.filename=foo.txt
foo.1.expire=200

foo.2.filename=foo2.txt
foo.2.expire=10

etc more foo's

bar.1.filename=bar.txt
bar.1.expire=100

where I'll assemble the filename/expire pairings into a data object, as part of an array for each parent property element like foo[myobject]

Formatting of the properties file can change, I'm open to ideas.

This question is related to java arrays enums properties

The answer is


Actually all answers are wrong

Easy: foo.[0]filename


I highly recommend using Apache Commons (http://commons.apache.org/configuration/). It has the ability to use an XML file as a configuration file. Using an XML structure makes it easy to represent arrays as lists of values rather than specially numbered properties.


I have custom loading. Properties must be defined as:

key.0=value0
key.1=value1
...

Custom loading:

/** Return array from properties file. Array must be defined as "key.0=value0", "key.1=value1", ... */
public List<String> getSystemStringProperties(String key) {

    // result list
    List<String> result = new LinkedList<>();

    // defining variable for assignment in loop condition part
    String value;

    // next value loading defined in condition part
    for(int i = 0; (value = YOUR_PROPERTY_OBJECT.getProperty(key + "." + i)) != null; i++) {
        result.add(value);
    }

    // return
    return result;
}

Use YAML files for properties, this supports properties as an array.

Quick glance about YAML:

A superset of JSON, it can do everything JSON can + more

  1. Simple to read
  2. Long properties into multiline values
  3. Supports comments
  4. Properties as Array
  5. YAML Validation

here is another way to do by implementing yourself the mechanism. here we consider that the array should start with 0 and would have no hole between indice

    /**
     * get a string property's value
     * @param propKey property key
     * @param defaultValue default value if the property is not found
     * @return value
     */
    public static String getSystemStringProperty(String propKey,
            String defaultValue) {
        String strProp = System.getProperty(propKey);
        if (strProp == null) {
            strProp = defaultValue;
        }
        return strProp;
    }

    /**
     * internal recursive method to get string properties (array)
     * @param curResult current result
     * @param paramName property key prefix
     * @param i current indice
     * @return array of property's values
     */
    private static List<String> getSystemStringProperties(List<String> curResult, String paramName, int i) {
        String paramIValue = getSystemStringProperty(paramName + "." + String.valueOf(i), null);
        if (paramIValue == null) {
            return curResult;
        }
        curResult.add(paramIValue);
        return getSystemStringProperties(curResult, paramName, i+1);
    }

    /**
     * get the values from a property key prefix
     * @param paramName property key prefix
     * @return string array of values
     */
    public static String[] getSystemStringProperties(
            String paramName) {
        List<String> stringProperties = getSystemStringProperties(new ArrayList<String>(), paramName, 0);
        return stringProperties.toArray(new String[stringProperties.size()]);
    }

Here is a way to test :

    @Test
    public void should_be_able_to_get_array_of_properties() {
        System.setProperty("my.parameter.0", "ooO");
        System.setProperty("my.parameter.1", "oO");
        System.setProperty("my.parameter.2", "boo");
        // WHEN 
        String[] pluginParams = PropertiesHelper.getSystemStringProperties("my.parameter");

        // THEN
        assertThat(pluginParams).isNotNull();
        assertThat(pluginParams).containsExactly("ooO","oO","boo");
        System.out.println(pluginParams[0].toString());
    }

hope this helps

and all remarks are welcome..


I can suggest using delimiters and using the

String.split(delimiter)

Example properties file:

MON=0800#Something#Something1, Something2

prop.load(new FileInputStream("\\\\Myseccretnetwork\\Project\\props.properties"));
String[]values = prop.get("MON").toString().split("#");

Hope that helps


Didn't exactly get your intent. Do check Apache Commons configuration library http://commons.apache.org/configuration/

You can have multiple values against a key as in key=value1,value2 and you can read this into an array as configuration.getAsStringArray("key")


As user 'Skip Head' already pointed out, csv or a any table file format would be a better fitt in your case.

If it is an option for you, maybe this Table implementation might interest you.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to enums

Enums in Javascript with ES6 Check if value exists in enum in TypeScript Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? TypeScript enum to object array How can I loop through enum values for display in radio buttons? How to get all values from python enum class? Get enum values as List of String in Java 8 enum to string in modern C++11 / C++14 / C++17 and future C++20 Implementing Singleton with an Enum (in Java) Swift: Convert enum value to String?

Examples related to properties

Property 'value' does not exist on type 'EventTarget' How to read data from java properties file using Spring Boot Kotlin - Property initialization using "by lazy" vs. "lateinit" react-router - pass props to handler component Specifying trust store information in spring boot application.properties Can I update a component's props in React.js? Property getters and setters Error in Swift class: Property not initialized at super.init call java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US How to use BeanUtils.copyProperties?