As the title suggests, this post is all about creating and accessing a property file through Java codes. To carry out such activities, 4 important classes have to be used and those are File, Properties, FileInputStream and FileOutputStream.
Pic P1: Shows method to write to a .properties file
Pic P1 shows how to write properties to a .properties file. Now lets explore this code line-by-line
-
Line 26 tries to access a file on the specified file path.
-
Line 27 checks if the file exists on the specified file path.
-
Line 28 creates a new file if the file does not exist using createNewFile() method.
-
Line 35 assigns properties with key and value for the selected file using setProperty() method.
-
Line 36 writes the properties to the .properties file using store() method.
Pic P2: Shows method to read from a .properties file
-
Line 49 creates an Input Stream to read from a specific file
-
Line 50 loads the .properties files using the selected Input Stream
-
Line 54 extracts the key and key value using the get() method.
-
Line 56 The Input stream is closed once the stream is not in use.
Pic P3: Shows sample code to test read and write methods
Pic P4: Shows output of the code in P3
Author: Thiagu