Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet165/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   161   162   163   164   165   166   167   168   ...   245
Bog'liq
Java 17 Recipes

 How It Works
The Java Properties class helps you manage program properties. It allows you to 
manage the properties either via external modification (someone editing a property file) 
or internally by using the Properties.store() method.
The Properties object can be instantiated either without a file or with a preloaded 
file. The files that the Properties object read are in the form of [name]=[value] and are 
textually represented. If you need to store values in other formats, you must write to and 
read from a string.
If you are expecting the files to be modified outside the program (the user directly 
opens a text editor and changes the values), be sure to sanitize the inputs, like trimming 
the values for extra spaces and ignoring the case if need be.
ChApTer 8 InpuT And OuTpuT


325
To query the different properties programmatically, you call the 
getProperty(String) method, passing the string-based name of the property whose 
value you want to retrieve. The method returns null if the property is not found. 
Alternatively, you can invoke the getProperty (String,String) method, on which if 
the property is not found in the Properties object, it returns the second parameter as its 
value. It is a good practice to specify default values if the file doesn’t have an entry for a 
particular key.
Upon looking at a generated property file, you notice that the first two lines indicate 
the description of the file and the date when it was modified. These two lines start with #, 
which in Java property files is the equivalent of a comment. The Properties object skips 
any line starting with # when processing the file.
Note If you allow users to modify your configuration files directly, it is important 
to have validation when retrieving properties from the Properties object. One 
of the most common issues encountered in the value of properties is leading and/
or trailing spaces. If specifying a Boolean or integer property, be sure that they can 
be parsed from a string. At a minimum, catch an exception when trying to parse to 
survive an unconventional value (and log the offending value).

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   161   162   163   164   165   166   167   168   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling