- Java Property File Processing
- Java Properties file examples
- 1. Write to the properties file
- 2. Load a properties file
- 3. Load a properties file from classpath
- 4. Prints everything from a properties file
- Download Source Code
- References
- Java Read and Write Properties File Example
- Example 1: Reading a .properties file in Java
- Example 2: Java program to write a new key-value pair in properties file
- Properties File — Java Read & Write
- Java properties file reader example
- How to read a properties file line by line in java
- How to write a key and values to a properties file in java
- Conclusion
Java Property File Processing
Properties is a file extension for files mainly used in Java related technologies to store the configurable parameters of an application. Java Properties files are amazing resources to add information in Java. Generally, these files are used to store static information in key and value pair. Things that you do not want to hard code in your Java code goes into properties files. The advantage of using properties file is we can configure things which are prone to change over a period of time without the need of changing anything in code. Properties file provide flexibility in terms of configuration. Sample properties file is shown below, which has information in key-value pair.
Each parameter is stored as a pair of strings, left side of equal (=) sign is for storing the name of the parameter (called the key), and the other storing the value.
Configuration:
This is property file having my configuration FileName=Data.txt Author_Name=Amit Himani Website=w3resource.com Topic=Properties file Processing
First Line which starts with # is called comment line. We can add comments in properties which will be ignored by java compiler.
Below is the java program for reading above property file.
package propertiesfile; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class PropertyFileReading < public static void main(String[] args) < Properties prop = new Properties(); try < // load a properties file for reading prop.load(new FileInputStream("myConfig.properties")); // get the properties and print prop.list(System.out); //Reading each property value System.out.println(prop.getProperty("FileName")); System.out.println(prop.getProperty("Author_Name")); System.out.println(prop.getProperty("Website")); System.out.println(prop.getProperty("TOPIC")); >catch (IOException ex) < ex.printStackTrace(); >> >
The program uses load( ) method to retrieve the list. When the program executes, it first tries to load the list from a file called myConfig.properties. If this file exists, the list is loaded else IO exception is thrown.
If File is not present in default project root location, we will get an exception like below, We can provide a fully qualified path of the file as well.
Use of getProperties() Method
One useful capability of the Properties class is that you can specify a default property that will be returned if no value is associated with a certain key. For example, a default value can be specified along with the key in the getProperty( ) method—such as getProperty(“name”,“default value”). If the “name” value is not found, then “default value” is returned. When you construct a Properties object, you can pass another instance of Properties to be used as the default properties for the new instance.
Writing Properties file
At any time, you can write a Properties object to a stream or read it back. This makes property lists especially convenient for implementing simple databases. For Example below program writes states can capital cities. “capitals.properties” file having state name as keys and state capital as values.
package propertiesfile; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class PropertyFileWriting < public static void main(String args[]) < Properties prop = new Properties(); try < // set the properties value prop.setProperty("Gujarat", "Gandhinagar"); prop.setProperty("Maharashtra", "Mumbai"); prop.setProperty("Madhya_Pradesh", "Indore"); prop.setProperty("Rajasthan", "Jaipur"); prop.setProperty("Punjab", "mkyong"); prop.setProperty("Uttar_Pradesh", "Lucknow"); // save properties to project root folder prop.store(new FileOutputStream("capitals.properties"), null); >catch (IOException ex) < ex.printStackTrace(); >> >
After running the program we can see a new file created named “capitals.properties” under project root folder as shown below.
Web Apr 24 19:50:18 IST 2013 Uttar_Pradesh=Lucknow Madhyar_Pradesh=Indore Maharashtra=Mumbai Gujarat=Gandhinagar Panjab=mkyong Rajasthan=jaipur
- Properties file provide flexibility in terms of configuration in java based application.
- We can store information in a properties file which can be changed over a period of time like database connection properties, password, input file name or location etc.
- We can Read/Write property file using java.util.Properties library of Java.
Java Code Editor:
Previous: Writing file
Next: Java Serialization
Follow us on Facebook and Twitter for latest update.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Java Properties file examples
Normally, Java properties file is used to store project configuration data or settings. In this tutorial, we will show you how to read and write to/from a .properties file.
Properties prop = new Properties(); // set key and value prop.setProperty("db.url", "localhost"); prop.setProperty("db.user", "mkyong"); prop.setProperty("db.password", "password"); // save a properties file prop.store(outputStream, ""); // load a properties file prop.load(inputStream) // get value by key prop.getProperty("db.url"); prop.getProperty("db.user"); prop.getProperty("db.password"); // get all keys prop.keySet(); // print everything prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
A simple Maven project structure for testing.
1. Write to the properties file
Set the property key and value, and save it somewhere.
package com.mkyong; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class App1 < public static void main(String[] args) < try (OutputStream output = new FileOutputStream("path/to/config.properties")) < Properties prop = new Properties(); // set the properties value prop.setProperty("db.url", "localhost"); prop.setProperty("db.user", "mkyong"); prop.setProperty("db.password", "password"); // save properties to project root folder prop.store(output, null); System.out.println(prop); >catch (IOException io) < io.printStackTrace(); >> >
The path/to/config.properties is created.
#Thu Apr 11 17:37:58 SRET 2019 db.user=mkyong db.password=password db.url=localhost
2. Load a properties file
Load a properties file from the file system and retrieved the property value.
package com.mkyong; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class App2 < public static void main(String[] args) < try (InputStream input = new FileInputStream("path/to/config.properties")) < Properties prop = new Properties(); // load a properties file prop.load(input); // get the property value and print it out System.out.println(prop.getProperty("db.url")); System.out.println(prop.getProperty("db.user")); System.out.println(prop.getProperty("db.password")); >catch (IOException ex) < ex.printStackTrace(); >> >
localhost mkyong password
3. Load a properties file from classpath
Load a properties file config.properties from project classpath, and retrieved the property value.
db.url=localhost db.user=mkyong db.password=password
package com.mkyong; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class App3 < public static void main(String[] args) < try (InputStream input = App3.class.getClassLoader().getResourceAsStream("config.properties")) < Properties prop = new Properties(); if (input == null) < System.out.println("Sorry, unable to find config.properties"); return; >//load a properties file from class path, inside static method prop.load(input); //get the property value and print it out System.out.println(prop.getProperty("db.url")); System.out.println(prop.getProperty("db.user")); System.out.println(prop.getProperty("db.password")); > catch (IOException ex) < ex.printStackTrace(); >> >
localhost mkyong password
4. Prints everything from a properties file
Load a properties file config.properties from project classpath, and print out the keys and values.
package com.mkyong; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; public class App4 < public static void main(String[] args) < App4 app = new App4(); app.printAll("config.properties"); >private void printAll(String filename) < try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename)) < Properties prop = new Properties(); if (input == null) < System.out.println("Sorry, unable to find " + filename); return; >prop.load(input); // Java 8 , print key and values prop.forEach((key, value) -> System.out.println("Key : " + key + ", Value : " + value)); // Get all keys prop.keySet().forEach(x -> System.out.println(x)); Set objects = prop.keySet(); /*Enumeration e = prop.propertyNames(); while (e.hasMoreElements()) < String key = (String) e.nextElement(); String value = prop.getProperty(key); System.out.println("Key : " + key + ", Value : " + value); >*/ > catch (IOException ex) < ex.printStackTrace(); >> >
Key : db.user, Value : mkyong Key : db.password, Value : password Key : db.url, Value : localhost db.user db.password db.url
Download Source Code
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Java Read and Write Properties File Example
In this Java tutorial, learn to read properties file using Properties.load() method. Also we will use Properties.setProperty() method to write a new property into the .properties file.
Given below is a property file that we will use in our example.
firstName=Lokesh lastName=Gupta blog=howtodoinjava technology=java
2. Reading Properties File
In most applications, the properties file is loaded during the application startup and is cached for future references. Whenever we need to get a property value by its key, we will refer to the properties cache and get the value from it.
The properties cache is usually a singleton static instance so that application does not require to read the property file multiple times; because the IO cost of reading the file again is very high for any time-critical application.
Example 1: Reading a .properties file in Java
In the given example, we are reading the properties from a file app.properties which is in the classpath. The class PropertiesCache acts as a cache for loaded properties.
The file loads the properties lazily, but only once.
import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; public class PropertiesCache < private final Properties configProp = new Properties(); private PropertiesCache() < //Private constructor to restrict new instances InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties"); System.out.println("Reading all properties from the file"); try < configProp.load(in); >catch (IOException e) < e.printStackTrace(); >> //Bill Pugh Solution for singleton pattern private static class LazyHolder < private static final PropertiesCache INSTANCE = new PropertiesCache(); >public static PropertiesCache getInstance() < return LazyHolder.INSTANCE; >public String getProperty(String key) < return configProp.getProperty(key); >public Set getAllPropertyNames() < return configProp.stringPropertyNames(); >public boolean containsKey(String key) < return configProp.containsKey(key); >>
In the above code, we have used Bill Pugh technique for creating a singleton instance.
public static void main(String[] args) < //Get individual properties System.out.println(PropertiesCache.getInstance().getProperty("firstName")); System.out.println(PropertiesCache.getInstance().getProperty("lastName")); //All property names System.out.println(PropertiesCache.getInstance().getAllPropertyNames()); >
Read all properties from file Lokesh Gupta [lastName, technology, firstName, blog]
3. Writing into the Property File
Personally, I do not find any good reason for modifying a property file from the application code. Only time, it may make sense if you are preparing data for exporting to third party vendor/ or application that needs data in this format only.
Example 2: Java program to write a new key-value pair in properties file
So, if you are facing similar situation then create two more methods in PropertiesCache.java like this:
public void setProperty(String key, String value) < configProp.setProperty(key, value); >public void flush() throws FileNotFoundException, IOException < try (final OutputStream outputstream = new FileOutputStream("application.properties");) < configProp.store(outputstream,"File Updated"); outputstream.close(); >>
- Use the setProperty(k, v) method to write new property to the properties file.
- Use the flush() method to write the updated properties back into the application.properties file.
PropertiesCache cache = PropertiesCache.getInstance(); if(cache.containsKey("country") == false) < cache.setProperty("country", "INDIA"); >//Verify property System.out.println(cache.getProperty("country")); //Write to the file PropertiesCache.getInstance().flush();
Reading all properties from the file INDIA
And the updated properties file is:
#File Updated #Fri Aug 14 16:14:33 IST 2020 firstName=Lokesh lastName=Gupta technology=java blog=howtodoinjava country=INDIA
That’s all for this simple and easy tutorial related to reading and writing property files using java.
Properties File — Java Read & Write
This tutorial explains step by step to read and write a properties file in java with example You learned to read properties file with key and values as well as line by line and also write key and values to the properties file.
In this tutorial, How to read and write a properties file content in Java
Java properties file reader example
In this example, you will learn how to read a key and its values from a properties file and display it to console
Let’s declare the properties file
Create a properties object, Properties is a data structure to store keys and values in java
Create URL object using ClassLoader . getSystemResource method
Create a InputStream using url.openStream method
Load the properties content into the java properties object using the load method
Add try and catch block for IOExceptions and FIleNotFoundException
Oneway, Print the value using getProperty with the key of a properties object
Another way is to iterate properties object for the loop
First, get all keys using stringPropertyNames
using for loop print the key and values.
catch (FileNotFoundException fie) < fie.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >System.out.println(properties.getProperty("hostname")); Set keys = properties.stringPropertyNames(); for (String key : keys) < System.out.println(key + " - " + properties.getProperty(key)); >> >
How to read a properties file line by line in java
- created a File object with an absolute path
- Create BufferedReader using FileReader object
- get the First line of the properties file using readLine of BufferedReader
- Loop using while loop until the end of the line reached
- Print each line
> catch (FileNotFoundException e1) < e1.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >finally < try < br.close(); >catch (IOException e) < e.printStackTrace(); >> > >
How to write a key and values to a properties file in java
In this example, You can read and write a property using
- First create a File object
- Create a writer object using FileWriter
- Create properties object and add new properties or update existing properties if the properties file exists
- setProperties method do update or add key and values
- store method of properties object writes to the properties file, You have to add the comment which appends to the properties file as a comment
Here is a complete example read and write a properties file
catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> >
Conclusion
You learned to read a properties file with keys and values as well as line by line and also write keys and values to the properties file