In the tutorial , we will talk about how to read value from property files in java program. As we all know that property file are the best choice when it comes to configure the program without changing it's code. so lets see how to read value from property file in java
Le suppose we have a program where we are reading the values from property file in resource. Below is the code we would use.
You can download the source code from GitHub
You can download the source code from GitHub
The project Structure
Now look for App.java Code
package com.programinjava.learn.ReadPropertyFileDemo; /** * Read property file demo * */ public class App { public static void main( String[] args ) { // Now I will read the property value of property-key String valueOfKey = PropertyUtil.readProperty("property-key"); System.out.println(valueOfKey); } }
PropertyUtil Class Code:
package com.programinjava.learn.ReadPropertyFileDemo; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertyUtil { // define the path of property file private static final String PROPERTY_FILE_PATH="src/main/resources/app.properties"; public static String readProperty(String propName) { Properties prop = new Properties(); InputStream input = null; String propValue = null; try { input = new FileInputStream(PROPERTY_FILE_PATH); prop.load(input); propValue = prop.getProperty(propName); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return propValue; } }
Also read : how to read user input in java
Code Follow (Explanation):
- Basically we have first created new Maven project in eclipse .
- Created new folder called resource inside src/main/ and add new property file called app.property.
- Now , created new class file called App.java ( may be auto generated) , In that wee will create the main method for execution.
- After that we have created a utility class , where we have write the logic of reading property file( see PropertyUtil.java) and it will give use the value of key we will pass for read.
Hope this helps you if you like this post please share it with your friends and colleagues.
Also read :
Thanks for reading
Noeik
Also read :
- Common Elements in Two Sorted Arrays Program in java
- Most Frequent Occurring Item in an Array program in java
- Program in java for Array Rotation
- Program to get all the substring of the string in java
- Quick Sort Program in java using Array
Thanks for reading
Noeik
0 comments:
Post a Comment