Java tool for reading configuration files

Source: Internet
Author: User


During system development, some configuration files are read. To facilitate reading the preset values from the configuration file, I made a simple configuration file reading tool class. This class is mainly based on the open-source Apache project commons-configuration. Let's take a look at the implementation of this simple tool class.

/*** Copyright (c) 2005 zjhcsoft techonologies, Ltd. ** history: * 2010-3-4 14:10:33 created by tiwen */package COM. zjhcsoft. modules. configuration; import Java. util. iterator; import Java. util. list; import Org. apache. commons. configuration. *; import Org. slf4j. logger; import Org. slf4j. loggerfactory; import COM. zjhcsoft. common. util. stringutil;/*** system configuration file parameter acquisition class ** @ author <a href = "mailto: Tiwen@qq.com"> Ti Wen </a> * @ version 1.0 14:10:33 */public class systemconfiguration {Private Static logger log = loggerfactory. getlogger (systemconfiguration. class); Private Static systemconfiguration = new systemconfiguration (); Private Static list <string> locations; private systemconfiguration () {} public static systemconfiguration getinstance () {If (! Isread) {reload (); isread = true;} return systemconfiguration;}/*** reload the configuration file */public static void reload () {If (locations = NULL) {log. warn ("No configuration file, cannot read"); return;} // pre-clear the original configuration set compositeconfiguration. clear (); configuration conf = NULL; int Index = 0; int COUNT = 0; For (string location: locations) {If (stringutil. isvalid (location) {try {log. debug ("start to read the system configuration file [{}]", location); If (location. tolowercase (). endswith (". XML ") {conf = new xmlconfiguration (location);} else {conf = new propertiesconfiguration (location);} compositeconfiguration. addconfiguration (CONF); Index = 0; For (iterator <string> it = Conf. getkeys (); it. hasnext ();) {index ++; count ++; string key = it. next (); log. debug ("configuration file information: [Key = {}, value = {}]", key, Conf. getstring (key);} log.info ("[{}] After the configuration file is complete, systemconfig loads {} configuration information in total", location, index);} catch (configurationexception E) {log. error ("systemconfiguration reading system configuration error:", e) ;}} log.info ("all configuration files are complete, systemconfiguration has loaded {} configuration information in total ", count);} Private Static compositeconfiguration = new compositeconfiguration (); Private Static Boolean isread = false;/*** reads the key and returns a boolean result. If the corresponding key value is not found, return false * @ Param key * @ return boolean result */public static Boolean getboolean (string key) {return getboolean (Key, false);}/*** to read the key, returns the boolean result. If no corresponding key value is found, the default value * @ Param key * @ Param defaultvalue is returned. The default value * @ return boolean result */public static Boolean getboolean (string key, boolean defaultvalue) {return compositeconfiguration. getboolean (Key, defaultvalue);}/*** reads the key and returns the string result. If the corresponding key value is not found, return NULL * @ Param key * @ return key value string */public static string getstring (string key) {return getstring (Key, null );} /*** reads the key and returns the string result. If the corresponding key value is not found, returns the default value * @ Param key * @ Param ultultvalue default value * @ return key value string */public static string getstring (string key, string defaultvalue) {return compositeconfiguration. getstring (Key, defaultvalue);}/*** reads the key and returns the int result. If the corresponding key value is not found, returns 0 * @ Param key * @ return key value */public static int getint (string key) {return getint (Key, 0);}/*** to read the key, returns the int result. If no corresponding key value is found, the default value * @ Param key * @ Param defaultvalue is returned. The default value * @ return key value */public static int getint (string key, int defaultvalue) {return compositeconfiguration. getint (Key, defaultvalue);}/*** reads the key and returns the double result. If the corresponding key value is not found, returns the 0f * @ Param key * @ return key value */public static double getdouble (string key) {return getdouble (Key, 0d);}/*** to read the key, returns the double result. If no corresponding key value is found, the default value * @ Param key * @ Param defaultvalue is returned. The default value * @ return key value */public static double getdouble (string key, double defaultvalue) {return compositeconfiguration. getdouble (Key, defaultvalue);}/*** reads the key and returns the key result. If the corresponding key value is not found, returns 0 * @ Param key * @ return key value */public static byte getbyte (string key) {return getbyte (Key, (byte) 0 );} /*** read the key and return the key result. If the corresponding key value is not found, returns the default value * @ Param key * @ Param ultultvalue default value * @ return key value */public static byte getbyte (string key, byte defaultvalue) {return compositeconfiguration. getbyte (Key, defaultvalue);}/*** reads the key and returns the key result. If the corresponding key value is not found, returns the 0f * @ Param key * @ return key value */public static float getfloat (string key) {return getfloat (Key, 0f);}/*** to read the key, returns the key result. If the corresponding key value is not found, the default value * @ Param key * @ Param defaultvalue is returned. The default value * @ return key value */public static float getfloat (string key, float defaultvalue) {return compositeconfiguration. getfloat (Key, defaultvalue);}/*** reads the key and returns the key result. If the corresponding key value is not found, returns the 0l * @ Param key * @ return key value */public static long getlong (string key) {return getlong (Key, 0l);}/*** to read the key, returns the key result. If no corresponding key value is found, the default value * @ Param key * @ Param defaultvalue is returned. The default value * @ return key value */public static long getlong (string key, long defaultvalue) {return compositeconfiguration. getlong (Key, defaultvalue);}/*** reads the key and returns the key result. If the corresponding key value is not found, returns 0 * @ Param key * @ return key value */public static short getshort (string key) {return getshort (Key, (short) 0 );} /*** read the key and return the key result. If the corresponding key value is not found, the default value * @ Param key * @ Param ultultvalue is returned. The default value * @ return key value */public static short getshort (string key, short defaultvalue) {return compositeconfiguration. getshort (Key, defaultvalue);} public list <string> getlocations () {return locations;} public void setlocations (list <string> locations) {This. locations = locations ;}}

Based on the features of the commons-Configuration component, I can read the configuration file in a format other than properties or XML format at the same time. This tool class belongs to the singleton mode, that is, it can be shared to any JVM object at any time. In the spring container, you only need to specify the configuration file to automatically read the configuration file, the spring configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsdhttp://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  <bean id="systemConfiguration" class="com.zjhcsoft.modules.configuration.SystemConfiguration" init-method="getInstance">    <property name="locations">      <list>        <value>test.properties</value>        <value>test.xml</value>      </list>    </property>  </bean></beans>

The container object only needs to call the getinstance of the systemconfiguration class during initialization to obtain the singleton object. Then inject the configuration file to the locations member attribute. We can immediately retrieve the preset values in the configuration file without initializing this object. For example, prepare the test. properies configuration file and the test. xml configuration file.

Test. properies

abc=123tiwen=hello!tiwen

Test. xml

<?xml version="1.0" encoding="UTF-8"?><conf>  <node1>true</node1>  <node2>10000</node2></conf>

 

Java test example:

/*** Copyright (c) 2005 zjhcsoft techonologies, Ltd. ** history: * 2010-3-4 14:10:33 created by tiwen */package COM. zjhcsoft. modules. configuration; import Org. springframework. context. applicationcontext; import Org. springframework. context. support. classpathxmlapplicationcontext;/*** system configuration file parameter acquisition class ** @ author <a href = "mailto: tiwen@qq.com "> tiwen </a> * @ version 1.0 14:10:33 */public class systemconfigurationtest {public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext (" modules. XML "); system. out. println ("properties config. key tiwen = "+ systemconfiguration. getstring ("tiwen"); system. out. println ("properties config. key abc = "+ systemconfiguration. getstring ("ABC"); system. out. println ("XML config. key node1 = "+ systemconfiguration. getboolean ("node1"); system. out. println ("XML config. key node2 = "+ systemconfiguration. getint ("node2 "));}}

The output is as follows:

properties config. key tiwen=hello!tiwenproperties config. key abc=123xml config. key node1=truexml config. key node2=10000

The systemconfiguration class also provides multiple data type conversion interfaces. You can choose one based on your needs, but remember that the conversion class must correspond to the correct configuration value, for example, "123" cannot use the getboolean method. Otherwise, an exception occurs during type conversion.


Tool complete code: http://download.csdn.net/detail/tiwen818/3873255

Original article, if reproduced, please mark the author: Tian Wen csdn address: http://blog.csdn.net/tiwen818

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.