What is a Properties File in Java?
In Java, a properties file is a simple text-based file used to store configuration or settings in key-value pairs. It provides a convenient way to externalize application-specific parameters that can be easily modified without modifying the source code.
Properties File always stores information about the configuration parameters such as project configuration data such as URL, username, password, and project settings config like browser name, environment, and so on.
Properties files have a “.properties” extension.
Why do we need a Properties File?
Properties files provide a convenient way to store configuration settings or parameters that can be easily modified without modifying the source code. It is not always a best practice to store the values as hardcoded in the project.
With properties files, you can have different versions of the file tailored for specific environments (e.g., development, testing, production). Each environment can have its own set of configurations while sharing a common structure and keys.
How to write data in a Properties File?
You can write properties to a properties file using the Properties
class. Below is an example of how to do this:
package org.example;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class WritePropertiesExample {
public static void main(String args[]) {
// Creating properties files from Java program
Properties properties = new Properties();
try {
// userCreated.properties is created at the mentioned path
FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreated.properties");
properties.setProperty("username", "Vibha");
properties.setProperty("password", "Admin");
// store() method is used to write the properties into properties file
properties.store(fileOutputStream, "Sample way of creating Properties file from Java program");
fileOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
FileOutputStream: This class is used to create or overwrite the existing property file.
Pass this stream into the “store()” method of “Properties”, which writes the contents of the “Properties” object into the file.
The output of the above execution is
userCreated.properties file is created in src/test/resources.
![](https://qaautomation.expert/wp-content/uploads/2024/06/image-12.png?w=518)
The userCreated.properties file is shown below:
![](https://qaautomation.expert/wp-content/uploads/2024/06/image-13.png?w=719)
Thank you for completing this tutorial! I’m glad you found it helpful. Happy learning and cheers to your success!