0

I got this text file I need to parse, and I am looking for the more efficient way to do it.

The file structure is known and looks like this :

[section]
key=value
key=value

[section]
key=value

[section]
key=value

I have no way to know in advance how many [section] I will read, nor how much key & value there is in each section.

I am trying to find the best way to store this file in a collection. So far, I figured that the best collection tu use would be a Map>, so that each [section] would have its associated key-value attached.

The problems I am having is mostly to handle blank lines, as I am looking for new sections with a simple :

if(line.charAt(0) == '[')

and obviously, with blank lines this returns null.

Can anyone just give me heads up on this ?

aur8l
  • 125
  • 13

1 Answers1

0

Use a HashMap to store key value pairs of one section. And a Hashmap to store section Name with the Key Value Hashmap. Then read in line and check if it is a new Section with Regex. If so create a new entry with section Name and new HashMap for the Key Value pairs. If not split the line by "=" token and put in the actual section hashmap the new Key Value Pair. If no regex was found and split does not result in two parts it was neither new section or Key Value and the line will be dismissed.

HashMap<String,HashMap<String,String>> sections = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line = "";
HashMap<String,String> actualSection = null;
Pattern p = Pattern.compile("\\[(.*?)\\]"); // regex pattern for brackets
while ((line = br.readLine()) != null) { 
    Matcher m = p.matcher(line);
    if(m.find()){
        // found regex means new section
        actualSection = new HashMap<String,String>();
        sections.put(m.group(1), actualSection);
    } else{
        // read in new key Value pairs
        String[] parts = line.split("=");
        if(parts.length == 2 && actualSection != null){                     
            actualSection.put(parts[0],parts[1]);   
        }                       
    }
}

After that you have everything stored in sections variable and you can get desired value with

System.out.println(sections.get(SECTIONNAME).get(KEYNAME));
ArcticLord
  • 3,999
  • 3
  • 27
  • 47
  • Works like a charm. I already got the HashMap of HashMap idea working, but had trouble dealing with blank lines at the end of sections. – aur8l Dec 09 '15 at 16:23