您的位置:首页 > 编程语言 > Java开发

java读取xml和property配置文件的方法

2017-06-14 11:46 726 查看
在软件开发过程中,有很多时候会有配置项的设置,通常配置项均是以key-value键值对的形式出现的,而比较常用的配置文件为Property和XML两种。

XML配置文件解析-DOM

有以下配置文件config.xml,里面配置了不同的系统参数,类似于key-value的形式。

<?xml version = "1.0" encoding="UTF-8"?>
<switch>
<config key = "isNoticeUser" value="1" />
<config key = "userName" value="melody" />
<config key = "userPwd" value="123456" />
<config key = "userAge" value="28" />
<config key = "userSex" value="man" />
</switch>


使用DOM模式解析XML,是把整个XML文档当成一个对象来处理,会先把整个文档读入到内存里。是基于树的结构,通常需要加载整文档和构造DOM树,然后才能开始工作。

这里首先设计一个类ReadXMLConfig,用于读取xml文件并解析提取其中的内容,ReadXMLConfig类中维护一个HashMap,将读取的内容存以key-value放在HashMap中,另外有时候其中的配置可能在多个地方访问,因此我们可以将ReadXMLConfig类设计成一个单例模式。(需要引入jar包xerces.jar)

import java.io.File;
4000

import java.io.InputStream;
import java.util.HashMap;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
* @读取配置文件获得配置
*
*/
public class ReadXMLConfig {

// 单例模式ReadXMLConfig类中维护本来对象
private static ReadXMLConfig readXMLConfig;

// 存储xml中的键值对
private HashMap<String, String> confMap;

// 定义为private防止类外调用构造函数生成对象
private ReadXMLConfig() {
try {
initReadConfig("com" + File.separator + "config" + File.separator
+ "config.xml");
System.out.println("---------" + "com" + File.separator + "config"
+ File.separator + "config.xml");
} catch (Exception e) {
System.out.println("init config.xml failure!");
}
}

// 单例模式通过getInstance始终返回同一个readXMLConfig对象
public static ReadXMLConfig getInstance() {
if (null == readXMLConfig) {
readXMLConfig = new ReadXMLConfig();
}
return readXMLConfig;
}

// 读取配置文件并读入至hashmap中
private void initReadConfig(String xmlFileName) throws Exception {
InputStream input = ReadXMLConfig.class.getClassLoader()
.getResourceAsStream(xmlFileName);
if (input == null) {
input = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(xmlFileName);
}
if (input == null) {
throw new Exception(xmlFileName + "not found!");
}
try {
// 使用DOM方式解析xml文件,并将结果存至hashmap中
DOMParser parser = new DOMParser();
parser.parse(new InputSource(input));
Document m_config = parser.getDocument();
Element root = m_config.getDocumentElement();

NodeList nodeList = root.getElementsByTagName("config");

int confNum = nodeList.getLength();
confMap = new HashMap<String, String>();
for (int i = 0; i < confNum; i++) {
Element ele = (Element) nodeList.item(i);
if (!ele.getAttribute("key").equals("")) {
confMap.put(ele.getAttribute("key"),
ele.getAttribute("value"));
}
}
} catch (Exception e) {
System.out.println("init config.xml failure!");
} finally {
input.close();
}
}

// 通过类中的该方法获取hashmap中的值
public String getConfigValue(String key, String defaultValue) {
if (confMap == null) {
return defaultValue;
} else {
String result = confMap.get(key);
if (result != null && !result.equals("")) {
return result;
}
}
return defaultValue;
}
}


测试类如下:

import com.wkx.ReadXMLConfig;

public class Test {

public static void main(String[] args) {

String isNoticeUser = ReadXMLConfig.getInstance().getConfigValue(
"isNoticeUser", "123");
String userName = ReadXMLConfig.getInstance().getConfigValue(
"userName", "123");
String userPwd = ReadXMLConfig.getInstance().getConfigValue("userPwd",
"123");
String userAge = ReadXMLConfig.getInstance().getConfigValue("userAge",
"123");
String userSex = ReadXMLConfig.getInstance().getConfigValue("userSex",
"123");
String emailAddress = ReadXMLConfig.getInstance().getConfigValue("emailAddress",
"123456@sina.com");

System.out.println("isNoticeUser=" + isNoticeUser + ";userName="
+ userName + ";userPwd=" + userPwd + ";userAge=" + userAge
+ ";userSex=" + userSex+ ";emailAddress=" + emailAddress);
}
}


执行结果:isNoticeUser=1;userName=melody;userPwd=123456;userAge=28;userSex=man;emailAddress=123456@sina.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息