0

I am trying to parse a Properties file that has the following format:

CarModel=Prius
CarMake=Toyota
Option1=Transmission
OptionValue1a=Manual
OptionValue1b=Automatic
Option2=Brakes
OptionValue2a=Regular
OptionValue2b=ABS

My question is, what if there are various forms of the Properties file? For instance, what if a Properties file has 3 options for Option 1, and another Properties file has 2 options for Option 1? Right now my code looks like this:

Properties props = new Properties();
FileInputStream x = new FileInputStream(filename);
props.load(x);

String carModel = props.getProperty("CarModel");
if(!carModel.equals(null)){
    String carMake = props.getProperty("CarMake");
    String option1 = props.getProperty("Option1");
    String option1a = props.getProperty("OptionValue1a");
    String option1b = props.getProperty("OptionValue1b");

etc. I'm thinking I need a lot of 'if' statements, but I'm unsure how to implement them. Any ideas?

Brian
  • 189
  • 3
  • 13
  • may [Reflection API](http://stackoverflow.com/a/37632/517134) help you? – Yusuf K. Mar 13 '16 at 09:55
  • Please clarify the requirements. Does it mean that a property with multiple values will always look like `PropertyName+Number`? Or are you free to choose what a multi-valued properties file will look like? – vempo Mar 14 '16 at 07:03

2 Answers2

1

Are you sure you want to use a properties file? I suggest using YAML.

I am trying to parse a Properties file that has the following format:

CarModel: Prius
CarMake: Toyota
Transmission:
  - Manual
  - Automatic
Brakes:
  - Regular
  - ABS

Using SnakeYAML you can do

Map<String, Object> car = (Map) new Yaml().load(new FileReader(filename));

Note the lines starting with - are turned into a list.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

If you must stick with Properties, I suggest putting the list in a property.

CarModel=Prius
CarMake=Toyota
Options=Transmission Manual|Automatic,\
  Brakes Regular|ABS

This way you can read the options like

String options = prop.getProperty("Options");
for(String option : options.split("\\s*,\\s*")) {
    String[] parts = option.split("\\s+");
    String optionType = parts[0];
    String[] optionChoices = parts[1].split("[|]");
}

This way you can have any number of options with any number of choices.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130