单例模式 [ Properties ]

来源:互联网 发布:c语言定义全局变量 编辑:程序博客网 时间:2024/05/17 02:01
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;


public class ConfigManager {
private static ConfigManager cm = new ConfigManager();
private File file ;
private Properties props;
private ConfigManager(){
file = new File("Singleton.properties");
props = new Properties();
try {
props.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
synchronized public static ConfigManager getConfigManagerInstance(){
return cm;
}
public Object getConfigItem(String name, Object defaultVal){
Object val = props.getProperty(name);
if(val == null){
return defaultVal;
}
return val;
}
public boolean contains(Object value){
if(props.contains(value))
return true;
return false;
}

public static void main(String[] args) throws Exception{
ConfigManager cm = ConfigManager.getConfigManagerInstance();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do{
System.out.println("Properties item to read:");
String line = br.readLine();
if(line == "quit"){
break;
}
System.out.println(line + " : "+ cm.getConfigItem(line, null));
}while(true);
}
}
原创粉丝点击