Why can't I read .properties file in order?

836 Views Asked by At

I have a label.properties file like this:

text1:firstname
text2:middlename
text3:lastname
text4:username

I read the properties file using this code

package test;

import java.util.Enumeration;
import java.util.ResourceBundle;


public class labelclass {

    public static String read(int n) {

        ResourceBundle rb = ResourceBundle.getBundle("myfolder.label");
        Enumeration <String> keys = rb.getKeys();
        while (keys.hasMoreElements()) {
            for(int i=1; i<=n; i++){
                    String key = keys.nextElement();
            }
            String value = rb.getString(key);
            return value;
        }
    }

}

If I call read(2), It should return middlename. But it returns firstname The order at which it returns is like:

text2:middlename
text1:firstname
text4:username
text3:lastname

Why is this so?

2

There are 2 best solutions below

2
On BEST ANSWER

.properties files are loaded by ResourceBundle into a HashSet, which does not preserve order. The Enumeration object that you receive is just an iterator over the set.

I looked into the ListResourceBundle class and unfortunately it too returns an Enumeration object over a set that does not maintain order.

Edit: .properties will be loaded using InputStream in PropertyResourceBundle and stored in an instance of Properties that is internally represented by a Hashtable which too does not maintain order. So the order is lost quite early in the process and several times later on.

0
On

ResourceBundle works on a Set, which is inherently not ordered in any way. You can retrieve all element and it guarantees that there are no duplicate elements, but it does not conserve any order of elements.

This is why you can't access an element by its number and have to resort to your for loop. Sets are not meant to be accessed in an indexed fashion.