The Wayback Machine - https://web.archive.org/web/20240528233657/https://www.geeksforgeeks.org/how-to-create-and-modify-properties-file-form-java-program-in-text-and-xml-format/
Open In App

How to Create and Modify Properties File Form Java Program in Text and XML Format?

Last Updated : 21 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article, let us see how to create properties file using Java programs.

Java API got java.util.Properties class and it has several utility stores() methods to store properties in either Text or XML format. In order to store property in text format, Store() method can be used. storeToXML() is used to make  in XML format.

store() method took two parameters like Output Stream and Comments.

Text format creation:

Let us see how to create a properties file in a text format. As we are creating properties contents, a valid file path location needs to be given.

Java




import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
  
public class CreationOfTextOrientedProperties {
  
    public static void main(String args[])
        throws FileNotFoundException, IOException
    {
  
        // Creating properties files from Java program
        Properties properties = new Properties();
        
        // In the name of userCreated.properties, in the
        // current directory location, the file is created
        FileOutputStream fileOutputStream
            = new FileOutputStream(
                "userCreated.properties");
  
        // As an example, given steps how
        // to keep username and password
        properties.setProperty("username", "value1");
        properties.setProperty("password", "value2");
  
        // writing properties into properties file
        // from Java As we are writing text format,
        // store() method is used
        properties.store(
            fileOutputStream,
            "Sample way of creating Properties file from Java program");
  
        fileOutputStream.close();
    }
}


Output:

We are using store() to save the properties file in text format. As key-value pairs, they are set. i.e. key = value. Other than that, all are considered as comments and hence with # symbol, comments are placed.

Usage of properties in text format is helpful in many instances when the property contents are less, and the team of developers is often changing, and end-users are on the Non-IT side.

XML format creation:

In many instances, XML is needed which provides an easy-to-understand and efficient format for storing important sensitive information. Extensible Markup Language (XML) is a markup language, and it is having a set of rules for encoding documents, and they are understandable in both human-readable and machine-readable format. Here, let us see how to create via Java program

Java




import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
  
public class CreationOfXMLOrientedProperties {
  
    public static void main(String args[])
        throws FileNotFoundException, IOException
    {
  
        // Creating properties files from Java program
        Properties properties = new Properties();
  
        // In the name of userCreated.xml, in the current
        // directory location, the file is created
        FileOutputStream fileOutputStream
            = new FileOutputStream("userCreated.xml");
  
        // As an example, given steps how to keep username
        // and password
        properties.setProperty("username", "value1");
        properties.setProperty("password", "value2");
  
        // writing properties into properties file
        // from Java As we are writing in XML format,
        // storeToXML() method is used
        properties.storeToXML(
            fileOutputStream,
            "Sample way of creating Properties file from Java program");
  
        fileOutputStream.close();
    }
}


Output:

If we check out the output of XML, it has an equal opening and closing of entries.

The one created via java programs also has the same structure. It has started to have with <properties> and end with </properties>. Other than key-value pair sets, the text is treated as comments and hence they are inside the comment tags. Properties files are having key values only and here also it is declared within “entry” tags along with “key=” which means separate entries are given for each and every key-value pair.

Whenever the properties file contents are huge and having sensitive information like banking transactions, financial data, etc., it is better to go in XML format only. 

A convenient way of converting XML contents to Read-only Text Mode way

Java




import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
  
public class ConvertXMLToTextOrientedProperties {
    public static void main(String[] args)
        throws InvalidPropertiesFormatException, IOException
    {
        String outputPropertiesFile
            = "sampleapplication.properties";
        String inputXmlFile
            = "sampleapplicationProperties.xml";
  
        // Input XML File which contains
        // necessary information
        InputStream inputStream
            = new FileInputStream(inputXmlFile);
  
        // Output properties File
        OutputStream outputStream
            = new FileOutputStream(outputPropertiesFile);
  
        Properties properties = new Properties();
  
        // Load XML file that has necessary information
        properties.loadFromXML(inputStream);
  
        // Store to properties file via this way
        properties.store(
            outputStream,
            "Converted from sampleapplicationProperties.xml");
  
        // For sample testing let us get username--It is
        // nothing but "Geek"
  
        // As it is converted to .properties file,
        // we can get the values in this way
        System.out.println(properties.get("username"));
    }
}


Input file (sampleapplicationProperties.xml)

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Elegant way of converting sampleapplicationProperties.xml 
  to Sampleapplication.properties</comment>
<entry key="username">Geek</entry>
  <entry key="password">XXXXWeldoneXXXX</entry>
</properties>


Generated Output file(sampleapplication.properties)

And also as we have, System.out.println(properties.get(“username”)); , it displays

“Geek” as output. So loadFromXML() helps to load the XML file and converts that to text-oriented properties file by means of the store() and also as got converted, we can get the property values easily.

Conclusion :

In this article, we have seen the ways of creation of properties files from java programs. Enjoy them to your convenience. They are helpful in any part of the software project as properties files are key files that hold sensitive information and also as they are in key-value pairs either as text or XML format, dynamic usage is seen, and at any point of time, we can modify them easily too.



Similar Reads

Java Program Format Time in MMMM Format
In Java, The MMM format for months is a short form of the month using 3 characters. SimpleDateFormat class is used for implementing this format in java and you can import this package by using the following code. import java.text.SimpleDateFormat Example: Months Name(MMMM Format)MMM FormatJanuaryJanFebruaryFebMarchMarAprilAprMayMayJuneJunJulyJulAug
2 min read
Java Program to Format Time in AM-PM format
Date Time Class Format is used to display date and time and manipulate date and time in java and in addition to this it is also used for formatting date and time class in java across time zone associated data. So in order to import this class from a package called 'java.utils'. After importing this class one can create an object of the Date class i
4 min read
Servlet - welcome-file-list in web.xml
The web.xml file's welcome-file-list property is used to establish a list of welcome files. If you don't supply a file name while loading the project in the browser, the tag &lt;welcome-file-list&gt; is used to define the files that will be called by the server by default. The server looks for the welcome file in the following sequence by default:
2 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Spring MVC Application Without web.xml File
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. Here we will be creating and running Your First Spring MVC Application, whenever we are Configuring Dispatcher Servlet we
4 min read
How to Configure Dispatcher Servlet in web.xml File?
DispatcherServlet acts as the Front Controller for Spring-based web applications. So now what is Front Controller? So it is pretty simple. Any request is going to come into our website the front controller is going to stand in front and is going to accept all the requests and once the front controller accepts that request then this is the job of th
5 min read
Hibernate - Logging by Log4j using xml File
The process of Hibernate Logging by Log4j using an XML file deals with the ability of the computer programmer to write the log details of the file he has created by executing it permanently. The most important tools in Java language like the Log4j and Log back frameworks. These frameworks in Java language help the programmer to install and initiate
5 min read
Java Program to Extract Content From a XML Document
An XML file contains data between the tags so it is complex to read the data when compared to other file formats like docx and txt. There are two types of parsers which parse an XML file: Object-Based (e.g. D.O.M)Event-Based (e.g. SAX, StAX) In this article, we will discuss how to parse XML using Java DOM parser and Java SAX parser. Java DOM Parser
6 min read
Practice Tags :