Sunday, July 28, 2013

Read and Display the Properties from a Properties File

In this post, we are going to see how to read a properties from a Properties file.

Project Structure:
=======================================================
ReadingProperties
  Src
       com.ranga
          ReadProperties.java
          login.properties
=======================================================

ReadProperties.java
package com.ranga;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
* @author Ranga Reddy
* @version 1.0
*/

public class ReadProperties {
public static void main(String[] args) {
InputStream inputStream = null;
Properties properties = new Properties();
try {
inputStream = new FileInputStream("login.properties");
properties.load(inputStream);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("=========================================");
System.out.println("username: " + username + " : password: " + password);
System.out.println("=========================================");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
login.properties
=====================
username=ranga
password=reddy

Output:
=========================================
username: ranga : password: reddy
=========================================

Reading both Key and Values:
            // Reading the both key and values
Enumeration props = properties.propertyNames();
while (props.hasMoreElements()) {
String key = (String) props.nextElement();
String value = properties.getProperty(key);
System.out.println("Key: " + key + ", Value: " + value);
}

0 comments: