Sorting the properties in java - java

Is there a way to sort the Properties object in java?
I have the string which groups the Properties and checks whether the data is available in the map format.

You can find an example without sub-classing Properties and working with Java 8/9/10
By this way, keySet, keys and entrySet methods from Properties return sorted keys. Then method store save the properties file sorted too.
This code is
here
Properties properties = new Properties() {
private static final long serialVersionUID = 1L;
#Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
#Override
public Set<Map.Entry<Object, Object>> entrySet() {
Set<Map.Entry<Object, Object>> set1 = super.entrySet();
Set<Map.Entry<Object, Object>> set2 = new LinkedHashSet<Map.Entry<Object, Object>>(set1.size());
Iterator<Map.Entry<Object, Object>> iterator = set1.stream().sorted(new Comparator<Map.Entry<Object, Object>>() {
#Override
public int compare(java.util.Map.Entry<Object, Object> o1, java.util.Map.Entry<Object, Object> o2) {
return o1.getKey().toString().compareTo(o2.getKey().toString());
}
}).iterator();
while (iterator.hasNext())
set2.add(iterator.next());
return set2;
}
#Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};

Please use this example :
from the link : http://www.java2s.com/Tutorial/Java/0140__Collections/SortPropertieswhensaving.htm
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
public class Main{
public static void main(String[] args) throws Exception {
SortedProperties sp = new SortedProperties();
sp.put("B", "value B");
sp.put("C", "value C");
sp.put("A", "value A");
sp.put("D", "value D");
FileOutputStream fos = new FileOutputStream("sp.props");
sp.store(fos, "sorted props");
}
}
class SortedProperties extends Properties {
public Enumeration keys() {
Enumeration keysEnum = super.keys();
Vector<String> keyList = new Vector<String>();
while(keysEnum.hasMoreElements()){
keyList.add((String)keysEnum.nextElement());
}
Collections.sort(keyList);
return keyList.elements();
}
}

Consider that TreeMap is a sorted Map, then you can do:
//properties as they are:
System.out.println(System.getProperties());
//now sorted:
TreeMap<Object, Object> sorted = new TreeMap<>(System.getProperties());
System.out.println(sorted);

Related

Access treemap in another class and loop through the items

Here's my first Java class, which includes the TreeMap that I want to loop through:
package myFunctions;
import java.util.TreeMap;
public class myUrls {
public void main() {
TreeMap<String, String> getUrl = new TreeMap<String, String>();
getUrl.put("app1", "URL 1");
getUrl.put("app2", "URL 2");
}
// Print keys and values
for (String i : getUrl.keySet()) {
System.out.println("app name: " + i + " url: " + getUrl.get(i));
}
}
}
Here's my second class, where I want to take the previously mentioned TreeMap and loop through it:
package myFunctions;
public anotherClass() {
DA_devurl myUrls = new DA_devurl();
//Loop through the array and perform seperate actions for each keyvalue pair
}
In your first class, I recommend making your TreeMap a private instance variable with a getter method:
package functions;
import java.util.TreeMap;
public class MyUrls {
private TreeMap<String, String> getUrl;
public MyUrls() {
getUrl = new TreeMap<String, String>();
}
public void main() {
getUrl.put("app1", "URL 1");
getUrl.put("app2", "URL 2");
}
public TreeMap<String, String> getGetUrl() {
return this.getUrl;
}
}
Now, in your second class, all you need to do is call the getter method after creating an instance of your previous class, and then looping through its entries with the proper syntax:
package functions;
import java.util.TreeMap;
import java.util.Map;
public class AnotherClass {
public static void main(String args[]) {
MyUrls myUrl = new MyUrls();
// populates the TreeMap
myUrl.main();
TreeMap<String, String> urls = myUrl.getGetUrls();
// Loop through the array and perform seperate actions for each keyvalue pair
for (Map.Entry<String, String> entry : urls.entrySet()) {
// do something with entry.getKey() and entry.getValue()
}
}
}

How can i retrieve the key based on the value present in the multimap?

i have some keys which are pointing to many values in a multimap. how can i retrieve the key basing on the value present in the multimap. Here is my code.
package com.manoj;
import java.util.Set;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class GuavaMap
{
public static void main(String[] args)
{
Multimap regions = ArrayListMultimap.create();
regions.put("asia", "afganistan");
regions.put("asia", "bangladesh");
regions.put("asia", "inida");
regions.put("asia", "japan");
regions.put("asia", "burma");
regions.put("europe", "andorra");
regions.put("europe", "austria");
regions.put("europe", "belgium");
regions.put("europe", "cyprus");
regions.put("oceania","australia");
regions.put("oceania", "fiji");
regions.put("oceania", "nauru");
Set<String> keys = regions.keySet();
System.out.println("key\t\t\t"+"values\t\t\t");
System.out.println();
String comp = null;
for(String key : keys)
{
System.out.print(key);
System.out.println(regions.get(key));
}
}
}
the above code is providing me the output as follows
i need the region name basing on the country.
Example: if i give "australia" output should be "oceania"
you can invert it
Multimap<String, String> invregions = Multimaps.invertFrom(regions , ArrayListMultimap.<String, String>create());
and call get("yourcountry");
this will give you the keys containing your country
Firstly, I would like to suggest to not use raw types and explicitly mention Key and Value type while creating Map.
Regarding your question to retrieve key depending on value, you can iterate over all entries of the map to do the same like:
class GuavaMap
{
//Explicitly mentioned key and value both are Strings here
public static Multimap<String, String> regions = ArrayListMultimap.<String, String>create();
public static void main(String[] args)
{
regions.put("asia", "afganistan");
regions.put("asia", "bangladesh");
regions.put("asia", "inida");
regions.put("asia", "japan");
regions.put("asia", "burma");
regions.put("europe", "andorra");
regions.put("europe", "austria");
regions.put("europe", "belgium");
regions.put("europe", "cyprus");
regions.put("oceania","australia");
regions.put("oceania", "fiji");
regions.put("oceania", "nauru");
Set<String> keys = regions.keySet();
System.out.println("key\t\t\t"+"values\t\t\t");
System.out.println();
String comp = null;
for(String key : keys)
{
System.out.print(key);
System.out.println(regions.get(key));
}
//usage of below defined method
String region = getRegion("australia");
System.out.println("Region for australia:" + region);
}
// Function to get the region name i.e. key
public static String getRegion(String country){
for(Entry<String, String> entry : regions.entries()){
if(entry.getValue().equals(country))
return entry.getKey();
}
return "Not found";
}
}
Thanks for the reply.
i found a solution based on the list, map and hashmap
package com.manoj;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class NestedList
{
public static void main(String[] args)
{
List asia = Arrays.asList("afganistan","japan","india","pakistan","singapore","sri lanka");
List europe = Arrays.asList("albania","belarus","iceland","russia","norway","turkey");
List middleEast = Arrays.asList("australia","new zealand","samoa","tonga","vanuatu");
Map region = new HashMap<>();
region.put("asia",asia);
region.put("europe", europe);
region.put("middleeast" ,middleEast);
String reg = null;
String val = null;
for(Object key : region.keySet())
{
reg = key.toString();
Iterator it = ((List) region.get(key)).iterator();
while(it.hasNext())
{
val = it.next().toString();
if(val.equalsIgnoreCase("india"))//here you have to provide the country name
{
System.out.println(reg);
}
}
}
}
}

How to input the objects to a ArrayList <HashMap<String,Object>>

I have 1 object(Goods) have 2 attributes: String and boolean. How to input object Goods to ArrayList<HashMap<String, Object>> ? Because I want input ArrayList<HashMap<String, Object>> to SimpleAdapter
public class Goods {
private String goodsName;
private boolean isCheck = false;
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
}
package ngo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
Map<String, Goods> map = new HashMap<String, Goods>();
map.put(g.getGoodsName(), g);
List<Map<String, Goods>> list = new ArrayList<Map<String, Goods>>();
list.add(map);
System.out.println(list.get(0).get("foo").isCheck());
}
}
Displays true
This should be an acceptable, if simple, structure for the data parameter of SimpleAdapter's constructor. A more exhaustive example of it's use can be found here
The following is the basic example, not runnable in itself.
ArrayList<HashMap<String, Goods>> listOfMappedGoods = new ArrayList<HashMap<String, Goods>>();
HashMap<String, Goods> goodsList = new HashMap<String, Goods>();
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
goodsList.add(g.getGoodsName(), g);
listOfMappedGoods.add(goodsList);
The point to note, is that just like every new Goods object needs to be created using new Goods(), each new goodsList needs to be created also using new HashMap<String, Goods>().
If you use something like goodsList.clear(), then you are still referring to the original map that was first added to the listOfMappedGoods, so you will clear that instead.

Case-insensitive String Substitutor

I am using org.apache.commons.lang3.text.StrSubstitutor to parse a String. I have it setup similar to this:
StrSubstitutor sub = new StrSubstitutor(messageValues, "&(", ")");
String format = sub.replace("Information: &(killer) killed &(target)!");
This no longer works if I write the keys in different cases:
"Information: &(KILLER) killed &(TARGET)!"
Is there a way of making the keys for the String Substitutor case-insensitive?
I cannot use toLowerCase() because I only want the keys to be case-insensitive.
StrSubstitutor has a constructor that takes an instance of StrLookup. You can create an implementation of StrLookup that lowercases the keys its looking for before actually looking for them.
Here's how it looks like:
public class CaseInsensitiveStrLookup<V> extends StrLookup<V> {
private final Map<String, V> map;
CaseInsensitiveStrLookup(final Map<String, V> map) {
this.map = map;
}
#Override
public String lookup(final String key) {
String lowercaseKey = key.toLowerCase(); //lowercase the key you're looking for
if (map == null) {
return null;
}
final Object obj = map.get(lowercaseKey);
if (obj == null) {
return null;
}
return obj.toString();
}
}
Using this StrLookup implementation you don't need to worry about what kind of Map you're passing to the constructor.
The following test case returns succesfully, using the above implementation:
import org.apache.commons.lang3.text.StrSubstitutor;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
#Test
public class TestClass {
#Test
public void test() {
Map<String, String> messageValues = new HashMap<String, String>();
messageValues.put("killer", "Johnson");
messageValues.put("target", "Quagmire");
StrSubstitutor sub = new StrSubstitutor(new CaseInsensitiveStrLookup<String>(messageValues), "&(", ")", '\\');
String format2 = sub.replace("Information: &(killer) killed &(target)!");
String format = sub.replace("Information: &(KILLER) killed &(TARGET)!");
Assert.assertEquals(format, "Information: Johnson killed Quagmire!");
Assert.assertEquals(format2, "Information: Johnson killed Quagmire!");
}
}
You don't need to write a custom class. Assuming you can live with the log(n) access times, just use a case-insensitive TreeMap.
public static void main(String[] args) {
Map<String, String> m = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
m.put("foo", "bar");
StrSubstitutor sub = new StrSubstitutor(m);
String s = sub.replace("${FOO}");
System.out.println(s);
} // prints "bar"
I think this case-insensitive map would work:
import java.util.HashMap;
import java.util.Map;
public class CaseMap<V> extends HashMap<String, V> {
public CaseMap() {
}
public CaseMap(int capacity) {
super(capacity);
}
public CaseMap(int capacity, float loadFactor) {
super(capacity, loadFactor);
}
public CaseMap(Map<String, ? extends V> map) {
putAll(map);
}
public V put(String key, V value) {
return super.put(key.toUpperCase(), value);
}
public V get(Object key) {
if (!(key instanceof String)) return null;
return super.get(((String)key).toUpperCase());
}
}
If you don't control the creation of the messageValues map, you could build a CaseMap from it like this:
CaseMap<String> caseFreeMessageValues = new CaseMap<String>(messageValues);
And then build your StrSubstitutor like this:
StrSubstitutor sub = new StrSubstitutor(messageValues, "&(", ")");
String format = sub.replace("Information: &(KILLER) killed &(TARGET)!");
You might want to think about other methods of Map that should be overridden as well, such as containsKey.
In case you need flexibility with both the Map and the Tokens being case insensitive AND you are not in control of the map being built you can use something like this.
String replaceTokens(String str, Map<String, String> messageValues) {
if(tokenToValue == null || tokenToValue.size() < 1) return str;
StrSubstitutor caseInsensitiveTokenReplacer = new StrSubstitutor(new CaseInsensitiveStrLookup<>(messageValues),
"&(", ")", '\\');
return caseInsensitiveTokenReplacer.replace(str);
}
StrLookup Implementation
public class CaseInsensitiveStrLookup<V> extends StrLookup<V> {
private final Map<String, V> map = new TreeMap<String, V>(String.CASE_INSENSITIVE_ORDER);
public CaseInsensitiveStrLookup(final Map<String, V> map) throws NullValueKeyNotSupported {
if(map.containsKey(null)) throw new Exception(); // Dont want to support null
this.map.putAll(map);
}
#Override
public String lookup(final String key) {
V value = map.get(key);
if(value == null) return null;
return value.toString();
}}

Pulling values from a Java Properties file in order?

I have a properties file where the order of the values is important. I want to be able to iterate through the properties file and output the values based on the order of the original file.
However, since the Properties file is backed by, correct me if I'm wrong, a Map that does not maintain insertion order, the iterator returns the values in the wrong order.
Here is the code I'm using
Enumeration names = propfile.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
//do stuff
}
Is there anyway to get the Properties back in order short of writting my own custom file parser?
Extend java.util.Properties, override both put() and keys():
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.HashMap;
public class LinkedProperties extends Properties {
private final HashSet<Object> keys = new LinkedHashSet<Object>();
public LinkedProperties() {
}
public Iterable<Object> orderedKeys() {
return Collections.list(keys());
}
public Enumeration<Object> keys() {
return Collections.<Object>enumeration(keys);
}
public Object put(Object key, Object value) {
keys.add(key);
return super.put(key, value);
}
}
Nope - maps are inherently "unordered".
You could possibly create your own subclass of Properties which overrode setProperty and possibly put, but it would probably get very implementation-specific... Properties is a prime example of bad encapsulation. When I last wrote an extended version (about 10 years ago!) it ended up being hideous and definitely sensitive to the implementation details of Properties.
If you can alter the property names your could prefix them with a numeral or other sortable prefix and then sort the Properties KeySet.
Working example :
Map<String,String> properties = getOrderedProperties(new FileInputStream(new File("./a.properties")));
properties.entrySet().forEach(System.out::println);
Code for it
public Map<String, String> getOrderedProperties(InputStream in) throws IOException{
Map<String, String> mp = new LinkedHashMap<>();
(new Properties(){
public synchronized Object put(Object key, Object value) {
return mp.put((String) key, (String) value);
}
}).load(in);
return mp;
}
Dominique Laurent's solution above works great for me. I also added the following method override:
public Set<String> stringPropertyNames() {
Set<String> set = new LinkedHashSet<String>();
for (Object key : this.keys) {
set.add((String)key);
}
return set;
}
Probably not the most efficient, but it's only executed once in my servlet lifecycle.
Thanks Dominique!
Apache Commons Configuration might do the trick for you. I haven't tested this myself, but I checked their sources and looks like property keys are backed by LinkedList in AbstractFileConfiguration class:
public Iterator getKeys()
{
reload();
List keyList = new LinkedList();
enterNoReload();
try
{
for (Iterator it = super.getKeys(); it.hasNext();)
{
keyList.add(it.next());
}
return keyList.iterator();
}
finally
{
exitNoReload();
}
}
I'll add one more famous YAEOOJP (Yet Another Example Of Ordered Java Properties) to this thread because it seems nobody could ever care less about default properties which you can feed to your properties.
#see http://docs.oracle.com/javase/tutorial/essential/environment/properties.html
That's my class: surely not 1016% compliant with any possible situation, but that is fine for my limited dumb purposes right now. Any further comment for correction is appreciated so the Greater Good can benefit.
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Remember javadocs >:o
*/
public class LinkedProperties extends Properties {
protected LinkedProperties linkedDefaults;
protected Set<Object> linkedKeys = new LinkedHashSet<>();
public LinkedProperties() { super(); }
public LinkedProperties(LinkedProperties defaultProps) {
super(defaultProps); // super.defaults = defaultProps;
this.linkedDefaults = defaultProps;
}
#Override
public synchronized Enumeration<?> propertyNames() {
return keys();
}
#Override
public Enumeration<Object> keys() {
Set<Object> allKeys = new LinkedHashSet<>();
if (null != defaults) {
allKeys.addAll(linkedDefaults.linkedKeys);
}
allKeys.addAll(this.linkedKeys);
return Collections.enumeration(allKeys);
}
#Override
public synchronized Object put(Object key, Object value) {
linkedKeys.add(key);
return super.put(key, value);
}
#Override
public synchronized Object remove(Object key) {
linkedKeys.remove(key);
return super.remove(key);
}
#Override
public synchronized void putAll(Map<?, ?> values) {
for (Object key : values.keySet()) {
linkedKeys.add(key);
}
super.putAll(values);
}
#Override
public synchronized void clear() {
super.clear();
linkedKeys.clear();
}
private static final long serialVersionUID = 0xC00L;
}
In the interest of completeness ...
public class LinkedProperties extends Properties {
private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();
#Override
public Enumeration<?> propertyNames() {
return Collections.enumeration(keys);
}
#Override
public synchronized Enumeration<Object> elements() {
return Collections.enumeration(keys);
}
public Enumeration<Object> keys() {
return Collections.enumeration(keys);
}
public Object put(Object key, Object value) {
keys.add(key);
return super.put(key, value);
}
#Override
public synchronized Object remove(Object key) {
keys.remove(key);
return super.remove(key);
}
#Override
public synchronized void clear() {
keys.clear();
super.clear();
}
}
I dont think the methods returning set should be overridden as a set by definition does not maintain insertion order
Map<String, String> mapFile = new LinkedHashMap<String, String>();
ResourceBundle bundle = ResourceBundle.getBundle(fileName);
TreeSet<String> keySet = new TreeSet<String>(bundle.keySet());
for(String key : keySet){
System.out.println(key+" "+bundle.getString(key));
mapFile.put(key, bundle.getString(key));
}
This persist the order of property file
You must override also keySet() if you want to export Properties as XML:
public Set<Object> keySet() {
return keys;
}
See https://github.com/etiennestuder/java-ordered-properties for a complete implementation that allows to read/write properties files in a well-defined order.
OrderedProperties properties = new OrderedProperties();
properties.load(new FileInputStream(new File("~/some.properties")));
In some answers it is assumed that properties read from file are put to instance of Properties (by calls to put) in order they appear they in file. While this is in general how it behaves I don't see any guarantee for such order.
IMHO: it is better to read the file line by line (so that the order is guaranteed), than use the Properties class just as a parser of single property
line and finally store it in some ordered Collection like LinkedHashMap.
This can be achieved like this:
private LinkedHashMap<String, String> readPropertiesInOrderFrom(InputStream propertiesFileInputStream)
throws IOException {
if (propertiesFileInputStream == null) {
return new LinkedHashMap(0);
}
LinkedHashMap<String, String> orderedProperties = new LinkedHashMap<String, String>();
final Properties properties = new Properties(); // use only as a parser
final BufferedReader reader = new BufferedReader(new InputStreamReader(propertiesFileInputStream));
String rawLine = reader.readLine();
while (rawLine != null) {
final ByteArrayInputStream lineStream = new ByteArrayInputStream(rawLine.getBytes("ISO-8859-1"));
properties.load(lineStream); // load only one line, so there is no problem with mixing the order in which "put" method is called
final Enumeration<?> propertyNames = properties.<String>propertyNames();
if (propertyNames.hasMoreElements()) { // need to check because there can be empty or not parsable line for example
final String parsedKey = (String) propertyNames.nextElement();
final String parsedValue = properties.getProperty(parsedKey);
orderedProperties.put(parsedKey, parsedValue);
properties.clear(); // make sure next iteration of while loop does not access current property
}
rawLine = reader.readLine();
}
return orderedProperties;
}
Just note that the method posted above takes an InputStream which should be closed afterwards (of course there is no problem to rewrite it to take just a file as an argument).
As I see it, Properties is to much bound to Hashtable. I suggest reading it in order to a LinkedHashMap. For that you'll only need to override a single method, Object put(Object key, Object value), disregarding the Properties as a key/value container:
public class InOrderPropertiesLoader<T extends Map<String, String>> {
private final T map;
private final Properties properties = new Properties() {
public Object put(Object key, Object value) {
map.put((String) key, (String) value);
return null;
}
};
public InOrderPropertiesLoader(T map) {
this.map = map;
}
public synchronized T load(InputStream inStream) throws IOException {
properties.load(inStream);
return map;
}
}
Usage:
LinkedHashMap<String, String> props = new LinkedHashMap<>();
try (InputStream inputStream = new FileInputStream(file)) {
new InOrderPropertiesLoader<>(props).load(inputStream);
}
For those who read this topic recently:
just use class PropertiesConfiguration from org.apache.commons:commons-configuration2.
I've tested that it keeps properties ordering (because it uses LinkedHashMap internally).
Doing:
`
PropertiesConfiguration properties = new PropertiesConfiguration();
properties.read(new FileReader("/some/path));
properties.write(new FileWriter("/some/other/path"));
`
only removes trailing whitespace and unnecessary escapes.
For Kotlin users, here's a basic example that's functional for write operations. The order is simply determined by the order of your calls to setProperty(k,v).
Per Kotlin's documentation for MutableMap and MutableSet, they both:
preserve the entry iteration order.
Not all use cases are covered.
class OrderedProperties: Properties() {
private val orderedMap = mutableMapOf<Any, Any>()
override val entries: MutableSet<MutableMap.MutableEntry<Any, Any>>
get() = Collections.synchronizedSet(orderedMap.entries)
#Synchronized
override fun put(key: Any?, value: Any?): Any? {
key ?: return null
value ?: return null
orderedMap[key] = value
return orderedMap
}
override fun setProperty(key: String?, value: String?): Any? {
return this.put(key, value)
}
}
An alternative is just to write your own properties file using LinkedHashMap, here is what I use :
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
public class OrderedProperties {
private static Map<String, String> properties = new LinkedHashMap<String, String>();
private static OrderedProperties instance = null;
private OrderedProperties() {
}
//The propertyFileName is read from the classpath and should be of format : key=value
public static synchronized OrderedProperties getInstance(String propertyFileName) {
if (instance == null) {
instance = new OrderedProperties();
readPropertiesFile(propertyFileName);
}
return instance;
}
private static void readPropertiesFile(String propertyFileName){
LineIterator lineIterator = null;
try {
//read file from classpath
URL url = instance.getClass().getResource(propertyFileName);
lineIterator = FileUtils.lineIterator(new File(url.getFile()), "UTF-8");
while (lineIterator.hasNext()) {
String line = lineIterator.nextLine();
//Continue to parse if there are blank lines (prevents IndesOutOfBoundsException)
if (!line.trim().isEmpty()) {
List<String> keyValuesPairs = Arrays.asList(line.split("="));
properties.put(keyValuesPairs.get(0) , keyValuesPairs.get(1));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
lineIterator.close();
}
}
public Map<String, String> getProperties() {
return OrderedProperties.properties;
}
public String getProperty(String key) {
return OrderedProperties.properties.get(key);
}
}
To use :
OrderedProperties o = OrderedProperties.getInstance("/project.properties");
System.out.println(o.getProperty("test"));
Sample properties file (in this case project.properties) :
test=test2

Categories