- Java Examples To Work With Properties File (Read & Write)
- 2. Setting and Getting values from Properties
- 3. Writing into Properties File
- 4. Loading from a property file
- 5. Reading/Loading the property file from classpath
- 6. Conclusion
- 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
- Properties File — Shell Read & Write
- How to read properties in Python with example?
- How to read properties file line by line in java
- How to write a key and values to an properties file in java
- Conclusion
Java Examples To Work With Properties File (Read & Write)
In this tutorial, We’ll be learning how to read from and write to the properties file in java.
Java API priovides a class Properties which is part of java.util package.
The Properties class stores the set of key, value pairs as properties. It internally stores all properties in a Stream. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list stored as a string.
public class Properties extends Hashtable
Properties inherit from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.
2. Setting and Getting values from Properties
Properties class provides methods to set and get property using setProperty() and getProperty() methods.
public Object setProperty(String key, String value) public String getProperty(String key)
The above methods take only String values as a key-value pair. No other types are allowed.
package com.java.w3schools.blog.java.properties; import java.util.Properties; public class PropertiesSetGetExample < public static void main(String[] args) < Properties properties = new Properties(); properties.setProperty("IN", "India"); properties.setProperty("USA", "United States"); properties.setProperty("AUS", "Australia"); System.out.println("All properties : " + properties); System.out.println("Retrieving the properties by key "); String AUSValue = properties.getProperty("AUS"); System.out.println("Value for AUS key is " + AUSValue); String INValue1 = properties.getProperty("IN"); System.out.println("Value for IN key is " + INValue1); String USAValue1 = properties.getProperty("USA"); System.out.println("Value for USA key is " + USAValue1); >>
All properties : Retrieving the properties by key Value for AUS key is Australia Value for IN key is India Value for USA key is United States
3. Writing into Properties File
public void store(OutputStream out, String comments) throws IOException
We need to pass the file location where the file should be created and comments to the file. Providing comments value is optional. If we do not want to pass the comments then provide null.
package com.java.w3schools.blog.java.properties; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class WritingToPropertyFile < public static void main(String[] args) < Properties properties = new Properties(); properties.setProperty("country.india", "Delhi"); properties.setProperty("country.australia", "Canberra"); properties.setProperty("country.usa", "Washington"); properties.setProperty("country.uae", "Abu Dhabi"); properties.setProperty("country.newzealand", "Wellington"); System.out.println("Writing the properties into a file"); try (OutputStream output = new FileOutputStream("files/application.properties")) < properties.store(output, "This is Country-Capital's property file"); System.out.println("Data stored into file"); >catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> >
Generated Properties file:
#This is Country-Capital's property file #Thu Aug 22 22:03:22 IST 2019 country.india=Delhi country.usa=Washington country.newzealand=Wellington country.australia=Canberra country.uae=Abu Dhabi
Added comments and file created date time to the property file.
4. Loading from a property file
Properties have a load() method that takes a file location.
public void load(InputStream inStream) throws IOException
Property file to be loaded:
welcome.message=Hello Mate, Welcome to Java8Example blog payment.creditcard=Enter Credit Card Number payment.netbanking=Select Your Bank payment.debitcard=Enter Debit Card Number payment.paypal=Enter PayPal Id
package com.java.w3schools.blog.java.properties; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class LoadingFromFile < public static void main(String[] args) < Properties properties = new Properties(); System.out.println("Writing the properties into a file"); try (InputStream input = new FileInputStream("files/payment.properties")) < properties.load(input); System.out.println("payment.properties loaded"); >catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >System.out.println(); String welcomeMsg = properties.getProperty("welcome.message"); System.out.println("welcome.message value : " + welcomeMsg); String netBanking = properties.getProperty("payment.netbanking"); System.out.println("payment.netbanking value : " + netBanking); String paypal = properties.getProperty("payment.paypal"); System.out.println("payment.paypal value : " + paypal); > >
Writing the properties into a file payment.properties loaded welcome.message value : Hello Mate, Welcome to Java8Example blog payment.netbanking value : Select Your Bank payment.paypal value : Enter PayPal Id
5. Reading/Loading the property file from classpath
Loading the file from the classpath is the same as above. But, Referring to the file location is different.
Just use the following line instread of new FileInputStream(«files/payment.properties»).
try (InputStream input = LoadingFromFile.class.getClassLoader().getResourceAsStream("payment..properties"))
6. Conclusion
In this article, We’ve covered working with Properties files.
How to set and get the properties. Writing the key-value pairs into the property file and loading from property files.
All examples shown are available on GitHub.
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
Properties File — Shell Read & Write
This tutorial explains step by step to read and write an properties file in java with example You learned read a properties file with key and values as well as line by line and also write key and values to properties file.
- How to read properties file using configparser in python
- Parse Properties file using JProperties library in phyton
- Write to Properties file in Python
How to read properties in Python with example?
In this example, you will learn how to Read key and its values from an properties file and display to console
Let’s declare properties file
Create a properties object, Properties is an data strucure to store key and values in java
Create URL object using ClassLoader . getSystemResource method
Create a InputStream using url.openStream method
Load the properties content into java properties object using load method
Add try and catch block for IOExceptions and FIleNotFoundException
Oneway, Print the value using getProperty with key of an properties object
Another way is to iterate properties object for 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 properties file line by line in java
- created a File object with absolute path
- Create BufferedReader using FileReader object
- get First line of properties file using readLine of BufferedReader
- Loop using while loop until end of 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 an properties file in java
In this example, You can read and write an properties using
- First create an File object
- Create a writer object using FileWriter
- Create properties object and add new properties or update existing properties if properties file exists
- setProperties method do update or add key and values
- store method of properties object writes to properties file, You have to add the comment which append to properties file as a comment
Here is an complete example read and write an properties file
catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> >
Conclusion
You learned read a properties file with key and values as well as line by line and also write key and values to properties file