Read the Key-Value of Properties Files in Java

In this section, you will learn how to read the
key-value of properties files in Java. This section
provides you an example for illustration how to read key and it's regarding
values from the properties file.
Program Result:
This program takes a property file name and reads
values according to the keys if the mentioned file exists, otherwise it shows the appropriate messages like: " File not
found!" and gives you a chance for entering properties file name through
the message "Enter file name that has properties extension:". This
message is shown until the entered file name exists.
If the file name exists then it takes the key and shows the values behalf
the entered key.
Code Description:
The following
methods and APIs are explained as follows, which have been used in the program:
Properties():
This is the constructor of Properties
class. Properties class extends the Hashtable.
This is the class of java.util.*
package. Above constructor creates an empty property list, which hasn't
any default values.
It uses the Keys and key-values of the properties file.
pro.load(InputStream in):
Above method reads the list of keys and values
(properties) from the given input stream. InputStream name is passed through the
method as a parameter.
pro.getProperty(String key_name):
This method finds the values of the given key
in the list of the keys and values from the stream. Key name is passed through
the method as a parameter.
Here is the code of program:
import java.io.*;
import java.util.*;
public class ReadProperty{
String str, key;
public static void main(String[] args) {
ReadProperty r = new ReadProperty();
}
public ReadProperty(){
try{
int check = 0;
while(check == 0){
check = 1;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file name which has properties extension :");
str = bf.readLine();
File f = new File(str + ".properties");
if(f.exists()){
Properties pro = new Properties();
FileInputStream in = new FileInputStream(f);
pro.load(in);
System.out.print("Enter Key : ");
key = bf.readLine();
String p = pro.getProperty(key);
System.out.println("Value : " + p);
}
else{
check = 0;
System.out.println("File not found!");
}
}
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
}
|
Download this example.

|