Thursday, December 9, 2010

Reading and Writing Properties

 

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.

 

image

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

  1. Line 26 tries to access a file on the specified file path.
  2. Line 27 checks if the file exists on the specified file path.
  3. Line 28 creates a new file if the file does not exist using createNewFile() method.
  4. Line 35 assigns properties with key and value for the selected file using setProperty() method.
  5. Line 36 writes the properties to the .properties file using store() method.

 

image

Pic P2:  Shows method to read from a .properties file

  1. Line 49 creates an Input Stream to read from a specific file
  2. Line 50 loads the .properties files using the selected Input Stream
  3. Line 54 extracts the key and key value using the get() method.
  4. Line 56 The Input stream is closed once the stream is not in use.

 

image

Pic P3: Shows sample code to test read and write methods

 

image

Pic P4: Shows output of the code in P3

 

Author: Thiagu

1 comment:

  1. In the writeProperty method we can also make use of this lines of code to avoid the loop.

    pro.putAll(keyValue);
    pro.store(new FileOutputStream(filepath), null);

    Thank you very much to my dear friend Sim for giving me this valuable comment.

    ReplyDelete