What is properties file?
A Properties file is used to store parameters and its values. Properties file has the extension .properties
Each parameter is stored as a pair of strings, one storing the name of the parameter called the key, and the other storing the value.
How to create a Properties file?
You can create properties file using any text editor and save the file with the extension .properties
How to read properties file in java
Here , you will learn how to read the key-value of properties files using Java with a simple example. Let’s consider properties file named sample.properties and which has some parameters like name and age .we can perform the following steps to read the values of these parameters.
Steps 1
Let us create a properties file called sample.properties , which has the following content and put it in our application root folder.
NAME=John
AGE=30
Step 2:
Write the java code to read this properties file and get the value of the parameter website
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.File; import java.io.FileInputStream; import java.util.Properties; public class ReadPropertiesFile { public static void main(String[] args) { FileInputStream in = null; Properties props = new Properties(); try { in = new FileInputStream(new File("sample.properties")); props.load(in); String name = props.getProperty("NAME"); String age = props.getProperty("AGE"); System.out.println("Name is - " + name); System.out.println("Age is - " + age); } catch (Exception e) { e.printStackTrace(); } } } |
Output:
Name is – John
Age is – 30
Getting all the keys defined in a properties file
The method propertyNames() will give you the list of all keys defined in the properties file and this method will return the Enumeration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.File; import java.io.FileInputStream; import java.util.Enumeration; import java.util.Properties; public class ReadPropertiesFile { public static void main(String[] args) { FileInputStream in = null; Properties props = new Properties(); try { in = new FileInputStream(new File("sample.properties")); props.load(in); Enumeration enumeration = (Enumeration) props.propertyNames(); while (enumeration.hasMoreElements()) { System.out.println(" Key: " + enumeration.nextElement()); } } catch (Exception e) { e.printStackTrace(); } } } |
The above code will display all the keys defined in the sample.properties file and the output is
Key: NAME
Key: AGE
Leave a Reply