Translate

Wednesday, June 2, 2010

Reading Property Files in Java

Property File Contents:

a = 1237
c = 6394
d = 84
f = 95867
k = 22597
m = 2

Solution:


import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
public class PropertyFileReader {
public static void main(String... args) throws IOException {
new PropertyFileReader().getPropertyFile();
}
private void getPropertyFile() throws IOException {
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("PropertyFile.properties"));
final int SIZE = properties.size();
Integer[] valArray = new Integer[SIZE];
Iterator iterator = properties.keySet().iterator();
int i = -1; // Don't change it to ZERO
HashMap hmTmpHashMap = new HashMap();// Temp HashMap to hold the elements from Property file for swaping keys with values
while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = (String) properties.get(key);
i++;
valArray[i] = new Integer(val);
hmTmpHashMap.put(valArray[i], key);
}
Arrays.sort(valArray); // Sorting Array of Values extracted from property file.
for(int k =0; k<SIZE; k++) {

System.out.println(hmTmpHashMap.get(valArray[k])+ " --- " + valArray[k] );
}
}
}

Out put:


m ---> 2
d ---> 84
a ---> 1237
c ---> 6394
k ---> 22597
f ---> 95867

No comments:

Post a Comment