*************************
ConfigManger.java
*************************
package propert;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class ConfigManger {
private static final String PFILE = "singleton.properties"; // 属性文件名
private File m_file = null; // 文件对象变量
private long m_lastModifiedTime = 0; // 属性文件的最后修改日期
private Properties m_props = null;// 属性对象变量
private static ConfigManger m_instance = new ConfigManger(); //本例可能存在的唯一的一个实例
private ConfigManger() {
m_file = new File(PFILE);
m_lastModifiedTime = m_file.lastModified();
if (m_lastModifiedTime == 0) {
System.err.println(PFILE + "file does not exits!");
}
m_props = new Properties();
try {
m_props.load(new FileInputStream(PFILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
synchronized public static ConfigManger getInstance() {
return m_instance;
}
final public Object getConfigItem(String name, Object defaultVal) {
long newTime = m_file.lastModified();
// 检查属性文件是否被修改,如果是,重读属性文件 if (newTime == 0) {
if (m_lastModifiedTime == 0) {
System.err.println(PFILE + "file does not exits!");
} else {
System.err.println(PFILE + "file was deleted!");
}
return defaultVal;
} else if (newTime > m_lastModifiedTime) {
m_props.clear();
try {
m_props.load(new FileInputStream(PFILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
m_lastModifiedTime = newTime;
Object val = m_props.getProperty(name);
if (val == null) {
return defaultVal;
} else {
return val;
}
}
}
*************************
AppMain.java
*************************
package propert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AppMain {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Type quit to quit!");
do {
System.out.print("Property item to read: ");
try {
String line = reader.readLine();
if (line.equals("quit")) {
break;
}
System.out.println(ConfigManger.getInstance().getConfigItem(
line, "NOT FOUND!"));
} catch (IOException e) {
e.printStackTrace();
}
} while (true);
}
}