Though most of the time we create and modify properties file using text editor like notepad, word-pad or edit-plus, It’s also possible to create and edit properties file from Java program. Log4j.properties, which is used to configure Log4J based logging in Java and jdbc.properties which is used to specify configuration parameters for database connectivity using JDBC are two most common example of property file in Java. Though I have not found any real situation where I need to create properties file using Java program but it’s always good to know about facilities available in Java API. In last Java tutorial on Properties we have seen how to read values from properties file on both text and XML format and in this article we will see how to create properties file on both text and XML format. Java API’s java.util.Properties class provides several utility store() methods to store properties in either text or xml format. Store() can be used to store property in text properties file and storeToXML() method can be used for creating a Java property file in XML format.
Java program to create and store Properties in text and XML format
As I said earlier java.util.Properties represent property file in Java program. It provides load() and store() method to read and write properties files from and to File system. Here is simple example of creating Java property file form program itself.
This will create user.properties file in C:\. here is how that property file will look like:
#Properties file generated from Java program
#Mon Jan 16 03:00:57 VET 2012
Here is another example of creating Java property file in XML format from Java program:
That’s all on How to create Properties file from Java program or How to modify Properties from Java program. As I said almost all time we use text editor e.g. notepad or notepad++ to edit properties file like log4j.properties or jdbc.properties, you can also edit them from Java program if needed. I personally prefer properties file in text format if number of properties is not much and XML based properties file if file is big enough e.g. if you have many properties to leverage XML editors.
Other Java XML tutorials you may find useful