import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
public class PropertiesUtil {
public static final Properties properties = new Properties();
public static final String path = PropertiesUtil.class.getResource("/application.properties").getFile();
public PropertiesUtil() throws FileNotFoundException {
//转换成流
InputStream inputStream = new FileInputStream(path);
try {
//从输入流中读取属性列表(键和元素对)
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 通过key获取value
* @param key
* @return
*/
public String get(String key) {
return properties.getProperty(key);
}
/**
* 修改或者新增key
* @param key
* @param value
*/
public void update(String key, String value) {
FileOutputStream oFile = null;
try {
if (StringUtils.isNotEmpty(get(key))){
delete(key);
}
properties.setProperty(key, value);
oFile = new FileOutputStream(path);
//将Properties中的属性列表(键和元素对)写入输出流
properties.store(oFile, "");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 通过key删除value
* @param key
*/
public void delete(String key) {
properties.remove(key);
FileOutputStream oFile = null;
try {
oFile = new FileOutputStream(path);
properties.store(oFile, "");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 循环所有key value
*/
public void list() {
Enumeration en = properties.propertyNames(); //得到配置文件的名字
while(en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = properties.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}