- To store configurable parameters, .properties file will be used in java.
- We can Store data in key value pair (key=value).
- Re compilation not required if we change any keys or values in properties file.
- Used for internationalization and to store frequently changeable values.
- java.util.Properties class is sub class of Hashtable.
- We can read / load the propertied file using InputStream.
- InputStream inputStream = getClass().getClassLoader().getResourceAsStream(properties_FileName);
- Create a maven project, under resources create one .properties file and load this file in main class using getClass().getClassLoader().getResourceAsStream(properties_FileName).
- Lets see an example java program on java read properties file from resource folder or how to read values from properties file in java example or how to get values from properties file in java.
#1: Create a maven project:
#1: Java example program to get values from properties file in java
- package com.instanceofjava.propertiesfile;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Date;
- import java.util.Properties;
- /**
- *
- * @author www.instanceofjava.com
- * @category: java example programs
- *
- * Write a java example program to read/ load properties file
- *
- */
- public class ReadPropertiesFile {
- public Properties getProperties() throws IOException {
- InputStream inputStream=null;
- Properties properties = new Properties();
- try {
- String propFileName = "config.properties";
- inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
- if (inputStream != null) {
- properties.load(inputStream);
- } else {
- throw new FileNotFoundException("property file '" + propFileName + "' not found
- in the classpath");
- }
- } catch (Exception e) {
- System.out.println("Exception: " + e);
- } finally {
- inputStream.close();
- }
- return properties;
- }
- public static void main(String[] args) throws IOException {
- ReadPropertiesFile obj= new ReadPropertiesFile();
- Properties properties=obj.getProperties();
- // get the each property value using getProperty() method
- System.out.println("username: "+properties.getProperty("username"));
- System.out.println("password: "+properties.getProperty("password"));
- System.out.println("url: "+properties.getProperty("url"));
- }
- }
Output:
- username: user1
- password: abc123
- url: www.instanceofjava.com
No comments