commons-configuration读取配置文件
Posted duenboa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了commons-configuration读取配置文件相关的知识,希望对你有一定的参考价值。
关键工具类:
- import org.apache.commons.configuration.CompositeConfiguration;
- import org.apache.commons.configuration.ConfigurationException;
- import org.apache.commons.configuration.PropertiesConfiguration; //读取properties配置文件
- import org.apache.commons.configuration.XMLConfiguration; //读取xml文件
-
我们在实际的开发设计中,通常要读各种各样的配置文件,十分烦琐.然而commons-configuration-1.0.jar为我们提供了非常方便的操作方式实例如下:1.读取XML文件中内容
- import java.util.List;
- import org.apache.commons.configuration.Configuration;
- import org.apache.commons.configuration.XMLConfiguration;
-
- public class XmlConfigurationExample {
-
- public static void main(String[] args) throws Exception {
- String resource = "com/discursive/jccook/configuration/global.xml";
- Configuration config = new XMLConfiguration(resource);
-
- List startCriteria = config.getList("start-criteria.criteria");
- int horsepower = config.getInt("horsepower");
- System.out.println( "Start Criteria: " + startCriteria );
- System.out.println(horsepower);
- }
- }
- global.xml
- <?xml version="1.0" encoding="ISO-8859-1" ?>
-
- <engine-config>
- <start-criteria>
- <criteria>
- Temperature Above -10 Celsius
- </criteria>
- <criteria>
- Fuel tank is not empty
- </criteria>
- </start-criteria>
- <volume>4 Liters</volume>
- <horsepower>42</horsepower>
- </engine-config>
2.读取properties文件
- import org.apache.commons.configuration.Configuration;
- import org.apache.commons.configuration.PropertiesConfiguration;
-
- public class PropertiesConfigurationExample {
-
- public static void main(String[] args) throws Exception {
- Configuration config = new PropertiesConfiguration(
-
- "com/discursive/jccook/configuration/global.properties" );
-
- System.out.println( "Speed: " + config.getFloat("speed"));
- System.out.println( "Names: " + config.getString("name"));
- }
- }
- global.properties
- threads.maximum=50
- threads.minimum=20
- timeout=15.52
- interactive=true
- color=red
- speed=50
- name=Default User
- email=default@email.com
- region=Earth
3.当有多个配置文件时,就利用ConfigurationFactory对象来访问多个不同的配置资源
- import java.net.URL;
- import java.util.List;
-
- import org.apache.commons.configuration.Configuration;
- import org.apache.commons.configuration.ConfigurationFactory;
-
- public class PropertiesXmlConfigurationExample {
-
- public static void main(String[] args) throws Exception {
- PropertiesXmlConfigurationExample example = new PropertiesXmlConfigurationExample();
-
- ConfigurationFactory factory = new ConfigurationFactory();
- URL configURL = example.getClass().getResource("additional-xml-configuration.xml");
- factory.setConfigurationURL( configURL );
-
- java:commons-configuration2与spring的集成
java中读取配置文件的方法
properties文件读取工具类
Configutation读取properties文件信息
加载配置文件工具类
关于JAVA 中的Configuration类