一个好的程序需要不懂代码的都能应用到自己服务器中。这时为了避免耦合需要配置文件。但对于配置文件我们需要怎么读取里面内容呢?下面是我整理的答案。
对于XML文件的解析
//在Classpath路径中得到Xml文件
public Document getDoc() {
try {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("actions.xml");
return builder.parse(is);
} catch (Exception e) {
throw new RuntimeException("在classpath根路径找不到action.xml文件", e);
}
}
//解析xml
Document doc = this.getDoc();
NodeList actionList = doc.getElementsByTagName("action");
for (int i = 0; i < actionList.getLength(); i++) {
Element action= (Element) actionList.item(i);
String name=action.getAttribute("name");
String className= action.getAttribute("class");
String method= action.getAttribute("method");
ActionConfig actionConfig = new ActionConfig();
actionConfig.setName(name);
actionConfig.setClassName(className);
actionConfig.setMethod(method);
actionMap.put(name, actionConfig);
//解析action中的result
NodeList resultList = action.getElementsByTagName("result");
for (int j = 0; j < resultList.getLength(); j++) {
Element result = (Element) resultList.item(j);
ResultConfig resultConfig = new ResultConfig();
String resultName = result.getAttribute("name");
resultConfig.setName(resultName);
resultConfig.setType(result.getAttribute("type"));
resultConfig.setPath(result.getTextContent());
actionConfig.getResultMap().put(resultName, resultConfig);
}
}
XML文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action name="emp" class="com.sheng.action.EmployeeAction" method="execute">
<result name="list" type="dispatcher">/views/emp/list.jsp</result>
<result name="edit" type="redirect">/views/emp/edit.jsp</result>
</action>
<action name="dept" class="com.sheng.action.DepartmentAction" method="execute"/>
</actions>
对于properties/ini文件的解析
/**
* @author Sun
* 读取Config文件夹中的Config.ini文件类容
*Properties类表示一个持久的属性集,他可保存在流中,或从流中加载,属性列表中的每一个
*键机器对应值都是一个字符串
*/
public class Config {
private static Properties p=null;
static{
try{
p=new Properties();
//加载配置文件
p.load(new FileInputStream("Config/Config.ini"));
}catch(Exception e){
e.printStackTrace();
}
}
//获取对应的键值
public static String getValue(String key){
return p.getProperty(key).toString();
}
}
配置文档内容如下:
server=127.0.0.1
msgport=8888
userport=8889
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/user
user=root
password=123456