first we have our properties file say for example data.properties
name = Rajkumar Singh
course = java
now create a singleton class as fallows
DataSingleton.java
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
package example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class DataSingleton {
static private DataSingleton instance = null;
public String name;
public String course;
static public DataSingleton getDataSingleton(){
if(instance == null){
instance = new DataSingleton();
}
return instance;
}
private DataSingleton(){
try{
BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));
Properties prop = new Properties();
prop.load(br);
name = prop.getProperty("name");
course = prop.getProperty("course");
}catch(IOException e){
e.printStackTrace();
}
}
}
now we have our tester class like this
TesterClass.java
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
public class TesterClass {
public static void main(String[] args) {
DataSingleton ds = DataSingleton.getDataSingleton();
System.out.println(ds.name);
System.out.println(ds.course);
}
}
output:
:::::::::::::::::::::::::::::::::::::::::::::::
Rajumar Singh
java
:::::::::::::::::::::::::::::::::::::::::::::::
the example is self explementory.......hope u enjoy the code segment
looking forward to your reply
No comments:
Post a Comment