优化,用于读写Properties文件,
在读取文件的时候给个默认值,如果不存在则得到的为默认值,存在就取文件中的值
{
private static final String CONFIG_FILE = "setting.properties";
private static final Properties pro = new Properties();
static {
try {
pro.load(new FileReader(CONFIG_FILE));
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String get(String key, String defaultValue) {
if (!pro.containsKey(key)) {
return defaultValue;
}
String value = pro.getProperty(key);
return value;
}
public static void set(String key, String value) {
pro.setProperty(key, value);
}
/**
* 保存方法,关闭流
*/
public static void save() {
FileWriter fos = null;
try {
try {
fos = new FileWriter(CONFIG_FILE);
pro.store(fos, "");
}
catch (Exception e) {
e.printStackTrace();
try {
if (fos != null) {
fos.flush();
fos.close();
}
}
catch (Exception e2) {
e2.printStackTrace();
}
}
}
finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// SystemConfig.set("英语","playEnglish");
// SystemConfig.set("体育","play");
// System.out.println(pro);
// SystemConfig.save();
System.out.println(SystemConfig.get("体育","语文111"));
}
}