读写Properties文件

public class PropertiesUtil {

public static Properties loadPropertFile(String filePath) {
Properties properties = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
properties.load(reader);
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}

/**
* 对指定的属性文件的指定键的值进行读取
*
* @param filePath
* @param key
* @return
*/
public static String readPropertByKey(String filePath, String key) {
String value = "";
Properties properties = loadPropertFile(filePath);
value = properties.getProperty(key);
return value;
}

/***
* 将键值对追写进指定的属性文件中
* @param filePath
* @param map
* @return
*/
public static boolean appendPropert(String filePath, Map<String, String> map) {
boolean flag = false;
Properties properties = loadPropertFile(filePath);
try {
OutputStream outputStream = new FileOutputStream(filePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
for(String key : map.keySet()){
properties.setProperty(key, map.get(key));
}
properties.store(bw, null);
outputStream.close();
flag = true;
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
}
posted @ 2017-08-25 16:04  程序虾  阅读(155)  评论(0编辑  收藏  举报