CasperPas
CasperPas

Reputation: 57

Java Parsing nested conf file

I have a config file:

company=My Company
num_users=3

user={
  name="John"
  age=24
}

user={
  name="Anna"
  age=27
}

user={
  name="Jack"
  age=22
}

I'm trying to parse this config file using Java. I tried java.util.Properties but I don't know how to get each single user data.

I still can get company property value using getProperty method.

Please help me with this.

Thanks!

Upvotes: 0

Views: 794

Answers (2)

jawee
jawee

Reputation: 271

If you use java.util.Properties class to load the config file, you will get the following result:

{company=My Company, age=22, user={, name="Jack", }=, num_users=3}

The reason, you could refer to the javaDoc for "public void load(Reader reader)" method of Properties class.

Since you don't describ the detailed syntax format for your config file, base on your example input, the following sample code could retrive the name=value correctly:

String reg="(\\w+)\\s*=\\s*((?>\\{[^\\{\\}]*\\})|(?>.*$))";
Pattern pMod = Pattern.compile(reg, Pattern.MULTILINE);
Matcher mMod = pMod.matcher(line);
while (mMod.find()) {
    System.out.println(mMod.group(1));
    System.out.println(mMod.group(2));
}

The output is:

company
My Company
num_users
3
user
{
  name="John"
  age=24
}
user
{
  name="Anna"
  age=27
}
user
{
  name="Jack"
  age=22
}

Upvotes: 1

Akash Thakare
Akash Thakare

Reputation: 22972

Nothing wrong with having same property name with different value but getProperty(String key) can not differentiate between them as it will return the first value.

Secondly you can not access nested property directly.Right now here getProperty will return whole String including {} as value because that's what your value contains.You may get value and perform some operations to fetch values from that whole String.Because property file should have only key=value format means left hand side should be key and right hand side should be value.That's it.

If you want to store values as you have specified in your code you should go for JSON format than you can store whole JSON data to file and get it back from the file while you want to use it.

Upvotes: 2

Related Questions