Jconfig 读xml

本文介绍了一个使用Java实现的配置文件加载与解析的过程。通过`ConfigurationManager`类实例加载了名为`config.xml`的配置文件,并展示了如何获取特定属性值。此过程涉及到了文件路径的设置、XML文件处理及异常捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args)
{
//找到配置文件的路径
String path = System.getProperty("user.dir") + "\\conf\\config.xml";

//ConfigurationManager 实例
ConfigurationManager cm = ConfigurationManager.getInstance();
//新建文件
File file = new File(path);
//XMLFIleHandler 类似于InputStreamHandler,setFile()需要set一个一个文件,而不是文件名。
XMLFileHandler xmlHeader = new XMLFileHandler();
xmlHeader.setFile(file);

try
{
cm.load(xmlHeader, "config");
}
catch (ConfigurationManagerException e)
{
e.printStackTrace();
}

//英文水平有限,官方说明如下
//A Configuraton provides access to all Category and Properties. The Configuration was converted into an Interface after the need for other Configuration implementations existed。
Configuration configuration = cm.getConfiguration("config");

//取配置文件general属性下所有节点的值。
//String[] arr = configuration.getPropertyNames("general");
/*System.out.println("arr.length=" + arr.length);
String key = null;
for(int i = 0; i < arr.length; i++)
{
key = arr[i];
System.out.println(configuration.getProperty(key));
}*/
String showNews = configuration.getProperty("showNews");
System.out.println(showNews);
}

附上config.xml
<?xml version="1.0" encoding="iso-8859-1" ?>
<properties>
<variables>
<variable name="my.path" value="/home/foo/data" />
</variables>
<category name="general">
<property name="upload_dir" value="${my.path}/data" />
<property name="NewsCounter" value="10" />
<property name="showNews" value="true" />
<property name="MyProp" value="Hello world" />
</category>
<category name="JDBC">
<property name="URL" value="jdbc:mysql://localhost/iportal" />
<property name="DRIVER" value="org.gjt.mm.mysql.Driver" />
<property name="PWD" value="pwd" />
<property name="USER" value="user" />
</category>
</properties>

说明:Jconfig读xml的时候传参数 my.path 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值