Better way to represent array in java properties file

JavaArraysEnumsProperties

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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")

Solution 3 - Java

Either define a delimiter that will not be a potential value or learn to use XML.

If you still insist on using properties use one of the methods that will return a list of all keys. Your key appears to have three parts a group identifier (foo, bar) an index (1, 2) and then an element name (filename, expire). Get all the keys break them into their component parts. Create a List for each type of identifier, when processing the list use the identifier to determine which List to add to. Create you paired elements as you said and simply add to the list! If the index order is important either add that as a field to your paired elements or sort the keys before processing.

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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..

Solution 8 - Java

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.

Solution 9 - Java

I'd suggest having the properties file, reference a CSV file. Then parse the CSV file into a collection/array etc instead. Properties file seems wrong fit for this kind of data.

Solution 10 - Java

Actually all answers are wrong

Easy: foo.[0]filename

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyepView Question on Stackoverflow
Solution 1 - JavaAbsView Answer on Stackoverflow
Solution 2 - JavaVenu KView Answer on Stackoverflow
Solution 3 - JavaBigMac66View Answer on Stackoverflow
Solution 4 - JavaSangeethView Answer on Stackoverflow
Solution 5 - JavasomtomasView Answer on Stackoverflow
Solution 6 - JavaJack CoxView Answer on Stackoverflow
Solution 7 - Javaboly38View Answer on Stackoverflow
Solution 8 - JavaOmnaestView Answer on Stackoverflow
Solution 9 - JavaJGFMKView Answer on Stackoverflow
Solution 10 - Javaqwert_ukgView Answer on Stackoverflow