Brian
Brian

Reputation: 189

Parsing Properties file

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?

Upvotes: 0

Views: 1060

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533520

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533520

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.

Upvotes: 1

Related Questions