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

在软件开发过程中,有很多时候会有配置项的设置,通常配置项均是以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;
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

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaXML 配置文件中,可以使用 Spring Framework 提供的 PropertyPlaceholderConfigurer 类来读取外部的 YAML 配置文件。以下是一个简单的示例: 首先,需要将 Spring Framework 库添加到项目的依赖中。如果使用 Maven,则可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.10</version> </dependency> ``` 然后,在 XML 配置文件中,可以通过以下方式读取 YAML 配置文件: ```xml <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.yaml</value> </list> </property> </bean> <bean id="myBean" class="com.example.MyBean"> <property name="server" value="${server}" /> <property name="port" value="${port}" /> <property name="database" value="${database}" /> </bean> ``` 在上面的示例中,PropertyPlaceholderConfigurer 类被用来加载外部的 YAML 配置文件。可以将文件名通过 locations 属性传递给该类的构造函数。在 XML 文件中,可以使用 ${key} 的形式来引用 YAML 文件中的键值对,其中 key 是 YAML 文件中的键名。 在 MyBean 类中,可以通过 setter 方法将 YAML 文件中的值注入到类的属性中: ```java public class MyBean { private String server; private int port; private String database; // setter methods @Override public String toString() { return "MyBean [server=" + server + ", port=" + port + ", database=" + database + "]"; } } ``` 需要注意的是,YAML 文件的格式必须正确,否则解析可能会失败。在使用 PropertyPlaceholderConfigurer 类时,还需要确保 XML 文件的命名空间和配置项都正确。可以参考 Spring Framework 的官方文档来了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值