📄 configload.java
字号:
package com.core.init;
/**
* 解析系统初始配置文件Config.xml,格式:
<mdgl-config>
<config name="LOGON_ACTION_NAME" value="wewe"/>
<config name="PAGE_SIZE" value="3"/>
</mdgl-config>
*/
import java.util.HashMap;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.InputStream;
import com.core.Config;
/**
* 加载Config.xml配置文件中的值,赋给Config的变量。
*/
public class ConfigLoad extends DefaultHandler {
private static Log log = LogFactory.getLog(ConfigLoad.class);
HashMap configMap = new HashMap();
public ConfigLoad(){
}
//在元属开始事件中进行的工作
public void startElement(String namespaceURI, String localName, String rawName, Attributes attrs) throws SAXException {
if (rawName.equals("config")) { //解析config节点
String name = attrs.getValue("name");
String value = attrs.getValue("value");
if (name == null || value == null) {
throw new SAXException("xml format error");
}
configMap.put(name, value);
log.info(name + "=" + value);
}
}
//在元属结束事件中进行的工作
public void endElement(String uri, String local, String rawName) throws SAXException {
}
//完成对xmlString的解析工作
public void parser(String strFilePath) {
try {
// 从类路径读取配置文件。
InputStream stream = this.getClass().getResourceAsStream(strFilePath);
if (stream == null) {
log.warn(strFilePath + " not found");
}
// 创建一个SAXParser解析器对象,并进行解析。
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
saxParser.parse(stream, this);
// 为全局变量赋值。
this.loadConfig(this.configMap);
} catch (Exception ex) {
log.error("加载 " + strFilePath + " 失败! 使用默认的配置.");
ex.printStackTrace();
}
}
// 把MDGLConfig.xml配置文件中的值,赋给Config的变量.
public void loadConfig(HashMap configMap) {
try {
Config.LOGON_ACTION_NAME = (String) configMap.get("LOGON_ACTION_NAME");
Config.PAGE_SIZE= Integer.parseInt((String) configMap.get("PAGE_SIZE"));
Config.UPLOAD_DIRECTORY = (String)configMap.get("UPLOAD_DIRECTORY");
} catch (Exception e) {
log.error("为系统配置参数赋值时出错!");
e.printStackTrace();
}
}
/* main method for test: */
public static void main(String[] args) {
ConfigLoad u = new ConfigLoad();
u.parser("F:\\config.xml");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -