Skip to content

PropertiesFileHandler

Raven Computing edited this page Mar 4, 2020 · 2 revisions

PropertiesFileHandler

Properties files are used to store plain key-value pairs in a text file. You can use the PropertiesFileHandler class to read and write such files.

Let's take a look at the following example properties file:

myKey1=42
myKey2=12345
#This is a comment
myKey3=Bla bla blub
myKey4=some text
myKey5=223

As you can see, all properties are simply declared line after line. Comments must start with a "#" and are excluded when you read a file. Duplicate keys are not allowed.

Read a .properties file

To read a .properties file from the filesystem simply construct a PropertiesFileHandler by passing the file you want to read, either as a File object or directly as a String, to the constructor. You can then call the read() method which will return a PropertiesFile object:

PropertiesFile props = new PropertiesFileHandler("myFile.properties").read();

You can then query all properties by calling the getProperty() method like this:

String value = props.getProperty("myKey3")

Or in order to set a property to a different value:

props.setProperty("myKey3", "myNewValue");

Please note that if there is no property for the specified key, it will be added to that PropertiesFile.

Write to a .properties File

You may want to persist a PropertiesFile object to a file after you have set or added a property. Simply call the write() method of the PropertiesFileHandler and pass the PropertiesFile object you want to persist as an argument:

new PropertiesFileHandler("myFile.properties").write(props);

NOTE: When you read a properties file, change an entry and then write it back to the filesystem, the structure and comments of that file are not preserved.

Clone this wiki locally