import org.apache.commons.lang3.StringUtils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Set;
/**
* @author lidg
* @date 2022/6/27
* @desc **.properties文件操作工具类
*/
public enum PropertiesUtil {
/**
* 实例
*/
INSTANCE;
/**
* application文件路径
*/
private String applicationFilePath = "application.properties";
/**
* 配置文件Properties
*/
private final Properties application = new Properties();
PropertiesUtil() {
init();
}
private PropertiesUtil init() {
// 获取配置文件绝对路径
String appFilePath = AppPathUtil.INSTANCE.getSourceAbsolutPath(applicationFilePath);
try (FileInputStream fileInputStream = new FileInputStream(appFilePath)) {
application.load(fileInputStream);
} catch (Exception e) {
// 部署配置文件加载错误
throw new RuntimeException("properties.load.error", e);
}
return this;
}
/**
* 配置要读取的配置文件相对于resource的路径
*
* @param propertiesPath 配置文件路径,没有值默认为resource下的application.properties
*
* @return
*/
public PropertiesUtil setPropertiesPath(String propertiesPath) {
if (StringUtils.isNotBlank(propertiesPath)) {
applicationFilePath = propertiesPath;
}
return init();
}
/**
* 新增配置文件属性
*
* @param key 键
* @param value 值
*/
public void addProperty(String key, String value) {
application.setProperty(key, value);
}
/**
* 设置配置文件属性
*
* @param key 键
* @param value 值
*
* @throws Exception
*/
public void setProperty(String key, String value) throws Exception {
propertyExists(key);
application.setProperty(key, value);
}
/**
* 获取配置文件属性
*
* @param key 键
*
* @return
*
* @throws Exception
*/
public String getProperty(String key) throws Exception {
propertyExists(key);
return application.getProperty(key);
}
/**
* 判断键是否存在于配置文件中
*
* @param key 键
*
* @throws Exception
*/
private void propertyExists(String key) throws Exception {
Set<String> names = application.stringPropertyNames();
if (!names.contains(key)) {
//配置文件中不存在此属性
throw new Exception();
}
}
/**
* 刷新properties文件
* @throws Exception
*/
public void updateProperties() throws Exception {
String appFilePath = AppPathUtil.INSTANCE.getSourceAbsolutPath(applicationFilePath);
try (FileOutputStream outputStream = new FileOutputStream(appFilePath)) {
application.store(outputStream, null);
} catch (Exception e) {
throw new Exception(e);
}
}
}
04-27
7803
