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