Home  >  Core Java

PropertyResourceBundle Java Example

By Arvind Rai, July 14, 2019
PropertyResourceBundle is the subclass of ResourceBundle. The ResourceBundle handles the resources for a given key value pair properties. PropertyResourceBundle can be created by InputStream or a Reader.

Read Property File

Here we will read a property file. Find the property file.
database.properties
database.driverClassName=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/concretepage
database.username=root
database.password=cp 
Find the code.
PropertyResourceBundleDemo1.java
package com.concretepage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;

public class PropertyResourceBundleDemo1 {
  public static void main(String[] args) {
	try {
	  InputStream propStrStream = new FileInputStream(new File("D:\\test\\database.properties"));
	  PropertyResourceBundle propBundle = new PropertyResourceBundle(propStrStream);
	  Enumeration<?> keys = propBundle.getKeys();
	  while (keys.hasMoreElements()) {
		String key = keys.nextElement().toString();

		System.out.println("key: " + key);
		System.out.println("Value: " + propBundle.getString(key));
		System.out.println("----------------");
	  }
	} catch (IOException e) {
	  e.printStackTrace();
	}
  }
} 
Output
key: database.url
Value: jdbc:mysql://localhost:3306/concretepage
----------------
key: database.username
Value: root
----------------
key: database.driverClassName
Value: com.mysql.cj.jdbc.Driver
----------------
key: database.password
Value: cp 
---------------- 

Read String Data

Here we will read string data.
PropertyResourceBundleDemo2.java
package com.concretepage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;

public class PropertyResourceBundleDemo2 {
  public static void main(String[] args) {
	String propStr = "user.name=Ram \n user.age=21 \n user.city=Noida";
	InputStream propStrStream = new ByteArrayInputStream(propStr.getBytes());
	try {
	  PropertyResourceBundle propBundle = new PropertyResourceBundle(propStrStream);
	  Enumeration<?> keys = propBundle.getKeys();
	  while (keys.hasMoreElements()) {
		String key = keys.nextElement().toString();
        
		System.out.println("key: " + key);
		System.out.println("Value: " + propBundle.getString(key));
		System.out.println("----------------");
	  }
	} catch (IOException e) {
	  e.printStackTrace();
	}
  }
} 
Output
key: user.age
Value: 21 
----------------
key: user.name
Value: Ram 
----------------
key: user.city
Value: Noida
---------------- 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us