Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
Multiline property values
Property files are a great way of storing application configuration information.
We can change the values in a simple properties text file and we don't have to recompile the complete application.
Anybody who has developed for the Windows platform will see the analogy with the INI files.
Property files can also be used for storing locale specific information.
For example all text appearing in the user interface can be stored in a properties file and very easy adapted to different locales and languages.
A property file has a key=value structure. Every line starts with the key followed by the equal sign and the value for the key followed by a new line. It is very important both key and value are on the same line. But sometimes the value can be very large and we want some way to divide the value over multiple lines so it is better to read. In this tip we will see how to accomplish this.
We start with a piece of code, which will read in a property file named tip59.properties.
try { Properties p = new Properties(); File file = new File("tip59.properties"); FileInputStream fis = new FileInputStream(file); p.load(fis); } catch (IOException ioex) { // Error reading property file ioex.printStackTrace(); }
We can now get property values from the Properties object by invoking the getProperty() method. Let's see the contents of the property file tip59.properties:
singleline=Single line value multiline =This example shows how we can write a property value over multiple lines in a fileWe notice two keys, singleline and multiline. The singleline value is one line and for the multiline value we have a longer value and to make it readable we have split the value in multiple lines.
Let's see what the values are we get when we invoke the getProperty() method of the Properties object:
System.out.println("singleline? " + p.getProperty("singleline")); System.out.println("multiline ? " + p.getProperty("multiline"));We get the following output:
singleline? Single line value multiline ? This example shows how weOnly the first line of our multiline value is assigned to the key. It is very easy to correct this problem. We have to use the escape character (\) at the end of every line, which belongs to the multiline key. We now have the following contents of the property file:
singleline=Single line value multiline =This example shows how we \ can write a property \ value over multiple lines in a \ fileIf we get the values from the changed property file, we get the following output:
singleline? Single line value multiline? This example shows how we can write a property value over multiple lines in a fileNow we have got the complete value for the multiline key.