How to store specific Key-Value Pairs from properties file - java

I want to store the key values pair in java from the config.properties file. Problem is it has some other which in dont want to store in array or hashmap.Below is my config.properties file. One thing the line must start with #usergroup and end of line should be End_TT_Executive as described in the file
#Usergroup
TT_Executive
#Tilename
KPI
#No of Submenu=3
#Submenu_1
OPs_KPI=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Submenu_2
Ontime_OnBudget=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_3
Ops_KPI_Cloud=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
Alerting Dashboard
#No of submenu=0
Alerting_Dashboard=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
FTE_Dashboard
#No of submenu=3
#Submenu_1
FTE_Market_Sector_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_2
FTE_Account_TT_Executive= http://tntanalytics1.sl1430087.sl.dst.ibm.com/ibmcognos/bi/?pathRef=.public_folders%2FP=false
#Submenu_3
FTE_Laborpool_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
PCR
#No of Submenu=0
PCR=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
End_TT_Executive
How can I do this? The key value pair are with URL only rest is some title for understanding.

Suppose your config.properties is like:
p1=abc
p2=def
p3=zxc
p4=eva
and you want to load p1 and p2 to map.
You can load all properties into Properties instance with:
InputStream inputStream = null;
try
{
inputStream = new BufferedInputStream(new FileInputStream("config.properties"));
Properties properties = new Properties();
properties.load(new InputStreamReader(inputStream, "UTF-8")); // load all properties in config.properties file
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
inputStream.close();
}
Then you create a map:
Map<String, String> propertyMap = new HashMap<>();
You also need a String[] to store all properties which you want to load to propertyMap.
String[] wantedProperties = new String[]{"p1", "p2"};
Then you write a for loop to load the properties you wanted:
for (String property : wantedProperties) {
propertyMap.put(property, properties.getProperty(property));
}
Now propertyMap is what you want.
If you want to store to List:
List<String> propertyList = new ArrayList<>();
for (String property : wantedProperties) {
propertyList.add(properties.getProperty(property));
}
This is the way to save to list. It'll help you more if you find the solution yourself.

Related

Load commented properties to Properties object in java

I'm trying to load properties to a Properties object in java using load(new FileReader()) method. All the properties are loaded except the properties start with(#) commented ones. How to load these commented properties to the Properties object using java API. Only manual way?
Thanks in Advance.
I could propose you to extend the java.util.Properties class to override this specificities but it was not designed for it : many things are hardcoded and not overridable. So you should do entire copy-paste of methods with little modification.
For example, at a time, the LineReader used in internal does that when you load a properties file :
if (isNewLine) {
isNewLine = false;
if (c == '#' || c == '!') {
isCommentLine = true;
continue;
}
}
The # is hardcoded.
Edit
Another way could be read line by line the proprties file, remove the first char if it is # and write the read line, modified if needed, in a ByteArrayOutputStream. then you could load the properties with a ByteArrayInputStream from ByteArrayOutputStream.toByteArray().
Here a possible implementation with a unit test :
With as input myProp.properties :
dog=woof
#cat=meow
The unit test :
#Test
public void loadAllPropsIncludingCommented() throws Exception {
// check properties commented not retrieved
Properties properties = new Properties();
properties.load(LoadCommentedProp.class.getResourceAsStream("/myProp.properties"));
Assert.assertEquals("woof", properties.get("dog"));
Assert.assertNull(properties.get("cat"));
// action
BufferedReader bufferedIs = new BufferedReader(new FileReader(LoadCommentedProp.class.getResource("/myProp.properties").getFile()));
ByteArrayOutputStream out = new ByteArrayOutputStream();
String currentLine = null;
while ((currentLine = bufferedIs.readLine()) != null) {
currentLine = currentLine.replaceFirst("^(#)+", "");
out.write((currentLine + "\n").getBytes());
}
bufferedIs.close();
out.close();
// assertion
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
properties = new Properties();
properties.load(in);
Assert.assertEquals("woof", properties.get("dog"));
Assert.assertEquals("meow", properties.get("cat"));
}

Read and write arrayList of Objects by using HashMap

I want to write and read 'HashMap' to file.
My 'HashMap' is:
Map<String, ArrayList<Descipline>> mapDis = new HashMap<String, ArrayList<Descipline>>();
and I write to file like this:
String root = Environment.getExternalStorageDirectory().toString();
Properties properties = new Properties();
for (Map.Entry<String, ArrayList<Descipline>> entry : mapDis.entrySet()){
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream(root + "/myMap.txt"), null);
But I don't know how to read it.
Map<String, ArrayList<Descipline>> load = new HashMap<String, ArrayList<Descipline>>();
Properties properties1 = new Properties();
properties1.load(new FileInputStream(root + "/myMap.txt"));
for (String key : properties1.stringPropertyNames()){
//something will be here to read file
}
You're already loaded the file. Within the loop you're reading the file (i.e. the map) entries so just use again the put method
It's simple really: java.util.Properties is a subclass of java.util.HashTable, which implements java.util.Map, just like java.util.HashMap does. So you can iterate using entrySet like you do when saving, giving you both the key and value.
Note however that Properties saving and loading expects both the key and value to be String (a .properties file is a simplified 'ini' file), so you might want to look into java.io.Serializable instead.

How to get the data after "=" sign from a txt file?

I have a program, in Java, that will save data to a .txt file and save it like:
intdata=2
stringdata=hello
How will I read the data from the text file and specify the value I need. Lets say I want the intdata value, it would return the part after the equals. How do I only return the part after the equals?
If you don't care about the key it's attached to: use String.split.
Scanner scan = new Scanner(new File("file.txt"));
String value = scan.nextLine().split("=")[1];
If you do care about the key it's attached to: use String.split in conjunction with a Map.
Scanner scan = new Scanner(new File("file.txt"));
Map<String, String> values = new HashMap<>();
while(scan.hasNextLine()) {
String[] line = scan.nextLine().split("=");
values.put(line[0], line[1]);
}
Alternatively, if it's a proper .properties file, you could elect to use Properties instead:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream("file.txt"));
// use it like a regular Properties object now.

How do I utilize a config file with my Java program?

I'm trying to use a config file that holds a list of hosts/websites and a time frequency for each one.
ex.
google.com 15s
yahoo.com 10s
My objective is to ping each website from the config file at every time period (15 secs).
Should I just read the config file and input the hosts/time into separate arrays?
Seems like there is a more efficient method...
Why use two arrays when the two items are so intimately related?
I'd put them into a Map:
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>();
pingUrlTimes.put("google.com", 15);
pingUrlTimes.put("yahoo.com", 10);
int pingTime = pingUrlTimes.get("google.com");
Here is a quick rundown of how to use a properties file.
You can create a file with the extension .properties (if under Windows make sure you have file extensions displayed) in the root of your project. The properties can be defined as pairs:
google.com=15
yahoo.com=10
In Java,
To get the ping time of a particular URL:
final String path = "config.properties";
Properties prop = new Properties();
int pingTimeGoogle = prop.load(new FileInputStream(path)).getProperty("google.com");
To cycle through the properties and get the whole list:
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + "=" + props.getProperty(key));
}
Edit: And here's a handy way to transform properties into a Map (Properties implements the Map interface):
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>((Map) props);
Cycling through the HashMap can be done like this:
Iterator iterator = pingUrlTimes.keySet().iterator(); // Get Iterator
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + "=" + pingUrlTimes.get(key) );
}

How to read and write a HashMap to a file?

I have the following HashMap:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
I write it to a file as follows:
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
Now I want to read this file back to a HashMap where the Object is an ArrayList.
If i simply do:
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object.
If you want it to serialize in the format that you desire you should write your own serializer/deserializer.
In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).
Thanks,
You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
I believe you´re making a common mistake. You forgot to close the stream after using it!
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
you can also use JSON file to read and write MAP object.
To write map object into JSON file
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Suson");
map.put("age", 26);
// write JSON to a file
mapper.writeValue(new File("c:\\myData.json"), map);
To read map object from JSON file
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\\myData.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
and import ObjectMapper from com.fasterxml.jackson and put code in try catch block
Your first line:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
gave me pause, as the values are not guaranteed to be Serializable and thus may not be written out correctly. You should really define the object as a HashMap<String, Serializable> (or if you prefer, simpy Map<String, Serializable>).
I would also consider serializing the Map in a simple text format such as JSON since you are doing a simple String -> List<String> mapping.
I believe you're getting what you're saving. Have you inspected the map before you save it? In HashMap:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
e.g. the default HashMap will start off with 16 nulls. You use one of the buckets, so you only have 15 nulls left when you save, which is what you get when you load.
Try inspecting fileObj.keySet(), .entrySet() or .values() to see what you expect.
HashMaps are designed to be fast while trading off memory. See Wikipedia's Hash table entry for more details.
Same data if you want to write to a text file
public void writeToFile(Map<String, List<String>> failureMessage){
if(file!=null){
try{
BufferedWriter writer=new BufferedWriter(new FileWriter(file, true));
for (Map.Entry<String, List<String>> map : failureMessage.entrySet()) {
writer.write(map.getKey()+"\n");
for(String message:map.getValue()){
writer.write(message+"\n");
}
writer.write("\n");
}
writer.close();
}catch (Exception e){
System.out.println("Unable to write to file: "+file.getPath());
e.printStackTrace();
}
}
}

Categories