Java – the best practice for reading a large number of custom settings from a text file

file handlingjava

So I have been looking through some code I wrote a few years ago for an economic simulation program. Each simulation has a large number of settings that can be saved to a file and later loaded back into the program to re-run the same/similar simulation. Some of the settings are optional or depend on what is being simulated.

The code to read back the parameters is basically one very large switch statement (with a few nested switch statements). I was wondering if there is a better way to handle this situation.

One line of the settings file might look like this:

#RA:1,MT:DiscriminatoryPriceKDoubleAuction,OF:Demo Output.csv,QM:100,NT:5000,KP:0.5 //continues...

And some of the code that would read that line:

switch( Character.toUpperCase( s.charAt(0) ) )
{
    case 'R':
         randSeed = Integer.valueOf( s.substring(3).trim() );
         break;
    case 'M':
          marketType = s.substring(3).trim();
          System.err.println("MarketType: " + marketType);
          break;
    case 'O':
          outputFileName = s.substring(3).trim() ;
          break;
    case 'Q':
          quantityOfMarkets = Integer.valueOf( s.substring(3).trim() );
          break;
    case 'N':
          maxTradesPerRound = Integer.valueOf( s.substring(3).trim() );
          break;
    case 'K':
          kParameter = Float.valueOf( s.substring(3).trim() );
          break;
 // continues...
}

Best Answer

From a code perspective, the cleanest method would be to switch to the Properties class. It's made for handling this, although you would either need to define all of your settings (even the unused ones) in the file it reads from or have predefined constants in a source file that you can use if the properties file returns null for a particular named property.

If you can't change the scheme, you could follow the general strategy of having a Hashtable, which is really what the Properties class does - it reads a file into a Hashtable conveniently. It would pretty much be rolling your own properties. Again, you would have to have preset values defined somehow to handle cases where a setting that you need might not exist in the file.

The way you would use either is to simply query the data structure any time you needed a value. You can either enforce that it exists in the data structure (throw an Exception and terminate it it doesn't) or define default values somehow (probably in a source file).

Related Topic