net.lulihu.ObjectKit.ConfigProperties Maven / Gradle / Ivy
package net.lulihu.ObjectKit;
import net.lulihu.exception.ToolBoxException;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.Properties;
/**
* 配置文件 属性解析工具
*/
public class ConfigProperties {
private Properties configuration = new Properties();
public ConfigProperties(String configFile) {
initConfig(configFile);
}
public ConfigProperties(File file) {
initConfig(file);
}
/**
* 初始化配置
*/
private void initConfig(File file) {
try (InputStream inputStream = new FileInputStream(file)) {
initConfig(inputStream);
} catch (IOException ex) {
throw new ToolBoxException(ex, "读取配置文件[{}]发送例外", file.getPath());
}
}
/**
* 初始化配置
*
* @param configFile 配置文件地址
*/
private void initConfig(String configFile) {
try (InputStream inputStream =
Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(configFile),
"配置文件不存在...")) {
initConfig(inputStream);
} catch (IOException ex) {
throw new ToolBoxException(ex, "读取配置文件[{}]发送例外", configFile);
}
}
/**
* 初始化配置
*/
private void initConfig(InputStream inputStream) throws IOException {
try (InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName("GBK"))) {
configuration.load(reader);
}
}
public String getStringValue(String key, String defaultValue) {
String value = getProperty(key);
return value == null ? defaultValue : value;
}
public String getStringValue(String key) {
String value = getProperty(key);
if (value != null) return value;
throw new NullPointerException("[" + key + "]不存在指定键的值...");
}
public Integer getIntValue(String key, int defaultValue) {
String value = getProperty(key);
if (value != null && value.length() > 0) {
return Integer.valueOf(value);
}
return defaultValue;
}
public Integer getIntValue(String key) {
String property = getStringValue(key);
return Integer.valueOf(property);
}
public Double getDoubleValue(String key) {
String property = getStringValue(key);
return Double.valueOf(property);
}
public Double getDoubleValue(String key, Double defaultValue) {
String value = getProperty(key);
if (value != null && value.length() > 0) {
return Double.valueOf(value);
}
return defaultValue;
}
public Long getLongValue(String key) {
String property = getStringValue(key);
return Long.valueOf(property);
}
public Long getLongValue(String key, Long defaultValue) {
String value = getProperty(key);
if (value != null && value.length() > 0) {
return Long.valueOf(value);
}
return defaultValue;
}
public Boolean getBooleanValue(String key) {
String property = getStringValue(key);
return Boolean.valueOf(property);
}
public Boolean getBooleanValue(String key, Boolean defaultValue) {
String value = getProperty(key);
if (value != null && value.length() > 0) {
return Boolean.valueOf(value);
}
return defaultValue;
}
/**
* 获取配置属性
*
* @param key 键
* @return UTF-8 编码的字符串
*/
private String getProperty(String key) {
return configuration.getProperty(key);
}
}