读写本地属性文件
package com.abc.utils;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertiesUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static final String GLOBAL_CONFIG_FILE = "props/common.properties";
private static PropertiesConfiguration configuration;
static {
try {
configuration = new PropertiesConfiguration(GLOBAL_CONFIG_FILE);
//自动重新加载
configuration.setReloadingStrategy(new FileChangedReloadingStrategy());
//自动保存
configuration.setAutoSave(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getString(String key) {
try {
//中文需要转码 ISO-8859-1 => UTF-8
return configuration.getString(key);
} catch (Exception e) {
logger.error("PropertiesUtil | method=getString() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
}
return null;
}
public static int getInt(String key){
try {
return configuration.getInt(key);
} catch (Exception e) {
logger.error("PropertiesUtil | method=getInt() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
}
return 0;
}
public static boolean getBoolean(String key){
try {
return configuration.getBoolean(key);
} catch (Exception e) {
logger.error("PropertiesUtil | method=getBoolean() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
}
return false;
}
public static boolean setProperty(String key, Object value) {
try {
//中文需要转码 UTF-8 => ISO-8859-1
configuration.setProperty(key, value);
return true;
} catch (Exception e) {
logger.error("PropertiesUtil | method=setProperty() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
}
return false;
}
}
Maven配置如下:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${commons.configuration.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons.beanutils.version}</version>
</dependency>