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
=====================
username=ranga
password=reddy
Output:
Reading both Key and Values:
Project Structure:
=======================================================
ReadingProperties
Src
com.ranga
ReadProperties.java
login.properties
=======================================================
ReadProperties.java
package com.ranga;login.properties
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();
}
}
}
}
}
=====================
username=ranga
password=reddy
Output:
=========================================
username: ranga : password: reddy
=========================================
// 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:
Post a Comment