1、BaseReader为基础类,为方便后续新增reader类使用
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BaseReader {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseReader.class);
private static Properties config = new Properties();
private static final Map<String, Map<String, String>> CONFIG_TYPE_MAPPING = new HashMap<String, Map<String, String>>();
protected BaseReader() {
}
protected static void readProperties(String[] filePaths, String keyword) {
for (String filePath : filePaths) {
InputStreamReader isr = null;
try {
InputStream resourceAsStream = BaseReader.class.getClassLoader().getResourceAsStream(filePath);
if (resourceAsStream == null) {
LOGGER.info("{} 文件不存在, 忽略", filePath);
continue;
}
isr = new InputStreamReader(resourceAsStream, "UTF-8");
config.load(isr);
} catch (IOException e) {
LOGGER.error("加载 {} 出错", filePath, e);
continue;
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
LOGGER.error("read {} config failed", filePath, e);
continue;
}
}
}
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<Object, Object> entry : config.entrySet()) {
String keyName = entry.getKey().toString();
String value = entry.getValue().toString();
if (keyName.contains(keyword)) {
map.put(keyName, value);
}
}
CONFIG_TYPE_MAPPING.put(keyword, map);
LOGGER.info("{} 文件配置读取成功", filePath);
}
}
/**
*
* @Description: 根据key找到对应的map
* @date 2017年8月11日 上午10:10:38
* @param key
* @return List<String>
*/
protected static Map<String, String> getMapping(String key) {
Map<String, String> map = CONFIG_TYPE_MAPPING.get(key);
return map != null ? map : new HashMap<String, String>();
}
}
2、 SmrzfsReader为demo
public final class SmrzfsReader extends BaseReader {
private static final String[] FILE_PATH = { "spring/is/is-smrz-mapping.properties", "override.properties" };
private static final String KEYWORD = "smrz_convert_";
static {
readProperties(FILE_PATH, KEYWORD);
}
private SmrzfsReader() {
}
/**
*
* @Description: 根据key找到value
* @date 2017年8月11日 上午10:10:38
* @param key
* @return List<String>
*/
public static String getValue(String key) {
return getMapping(KEYWORD).get(key);
}
}