Java Read Properties configuration file

Source: Internet
Author: User

1.Properties class and properties configuration file

The properties class inherits from the Hashtable class and implements the map interface, using the form of a key-value pair to hold the property set. However, the properties ' keys and values are string types.

The main methods in 2.Properties

(1) Load (InputStream instream)
This method can load a property list into the Properties class object from the file input stream corresponding to the. Properties property file. Used to read the properties configuration file.

Properties prop = new properties ();     Read the properties file A.propertiesinputstream in = new Bufferedinputstream (New FileInputStream ("A.properties"));p rop.load (in); Load Property list iterator<string> it=prop.stringpropertynames (). iterator (); while (It.hasnext ()) {String Key=it.next (    ); System.out.println (key+ ":" +prop.getproperty (Key));} In.close ();

(2) Store (OutputStream out, String comments)
This method saves the property list of the Properties class object to the output stream. Used to write properties configuration files.

Properties prop = new properties (); Save property to B.properties file FileOutputStream ofile = new FileOutputStream ("B.properties", true);// True means append open prop.setproperty ("Phone", "10086");p Rop.store (ofile, "Comment");//If comments is not empty, the first row of the saved properties file is #comments , which represents the comment information, or no comment if it is empty. The comment information is followed by the current save time information for the property file. Ofile.close ();

(3) Getproperty/setproperty
The two methods are to get and set property information, respectively.

3. Example

The following is a tool class written by Huang Yong to get the properties file.

/** *  Properties File Tool class  */public final class PropsUtil {     Private static final logger logger = loggerfactory.getlogger (PropsUtil.class);     /**     *  Load Properties File      */     public static properties loadprops (String filename)  {         Properties props = null;         inputstream is = null;        try  {            is =  Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (FileName);             if  (is == null)  {              &nBsp;  throw new filenotfoundexception (filename +  " file is not  found ");            }             props = new properties ();             props.load (IS);         } catch  (ioexception e)  {             logger.error ("Load properties file failure",  e);         } finally {             if  (is != null)  {                 try {                     is.close ();                 } catch  (ioexception e)  {                     logger.error ("Close  input stream failure ",  e);                 }            }         }        return  props;    }    /**     *  Get Character Type property (default is an empty string)      */    public static String  GetString (Properties props, string key)  {         Return getstring (PROPS,&NBSP;KEY,&NBSP; "");     }    /**     *  Get character attributes (you can specify default values)       */    public static string getstring (Properties  props, string key, string defaultvalue)  {         string value = defaultvalue;        if   (Props.containskey (key))  {             Value = props.getproperty (Key);        }         return value;    }    /**      *  Get numeric properties (default =  0)      */     Public static int getint (Properties props, string key)  {         return getint (props, key, 0);    }    //  Gets the numeric property (can specify a default value)     public static int getint (properties props,  String key, int defaultvalue)  {        int  value = defaultvalue;        if  (Props.containsKey (key) )  {            value =  Castutil.castint (Props.getproperty (key));        }         return value;    }    /**      *  Get Boolean property (default =  false)      */     public static boolean getboolean (Properties props, string key)  {        &nbsP;return getboolean (props, key, false);     }    /**      *  Get Boolean properties (you can specify default values)      */     Public static boolean getboolean (Properties props, string key, boolean  defaultvalue)  {        boolean value =  defaultvalue;        if  (Props.containskey (key))  {             value = castutil.castboolean ( Props.getproperty (key));        }         return value;    }}

/** *  Transformation Operation Tool class  */public final class castutil {    /**      *  switch to  String  type      */     public static string caststring (object obj)  {         return castutil.caststring (obj,  "");    }     /**     *  to  String  (default value provided)      */     public static string caststring (object obj, string  DefaultValue)  {        return obj != null ?  string.valueof (obj)  : defaultValue;    }    /**      *  switch to  double  type      */     public static double Castdouble (object obj)  {        return  Castutil.castdouble (obj, 0);    }    /**      *  to  double  (default value provided)      */    public  Static double castdouble (Object obj, double defaultvalue)  {         double doubleValue = defaultValue;         if  (obj != null)  {             string strvalue = caststring (obj);             if  (Stringutil.isnotempty (strvalue))  {                 try {            &nbSp;        doublevalue = double.parsedouble (StrValue);                 } catch  ( Numberformatexception e)  {                     doubleValue = defaultValue;                 }             }        }         return doubleValue;    }    /**      *  switch to  long  type      */     Public static long castlong (object obj)  {         return castutiL.castlong (obj, 0);     }    /**     *   to  long  (default value provided)      */    public static  long castlong (Object obj, long defaultvalue)  {         long longValue = defaultValue;         if  (obj != null)  {             string strvalue = caststring (obj);             if  (Stringutil.isnotempty (strvalue))  {                 try {                     longValue =  Long.parselong (strvalue);                 } catch  ( Numberformatexception e)  {                     longValue = defaultValue;                 }             }        }         return longValue;    }    /**      *  switch to  int  type      */    public  static int castint (object obj)  {         Return castutil.castint (obj, 0);    }    /**      *  Switch to &NBSP;INT&NBSP; Type (provides default value)      */    public static int castint ( Object obj, int defaultvalue)  {        int  intvalue = defaultvalue;        if  (obj !=  NULL)  {            String strValue  = caststring (obj);            if  ( Stringutil.isnotempty (strvalue))  {                 try {                     intvalue = integer.parseint (StrValue);                 } catch  ( Numberformatexception e)  {                     intValue = defaultValue;                 }            }         }        return  intvalue;    }    /**     *  converted to   boolean  type      */    public static boolean  Castboolean (object obj)  {        return  Castutil.castboolean (Obj, false);    }    /**      *  to  boolean  (default value provided)      */    public  static boolean castbooleaN (object obj, boolean defaultvalue)  {         boolean booleanvalue = defaultvalue;        if  ( Obj != null)  {             Booleanvalue = boolean.parseboolean (caststring (obj));         }        return booleanvalue;    }}

/** *  string tool class  */public  final class stringutil {    /**     *  Determines whether the string is empty      */    public static boolean isempty ( STRING&NBSP;STR)  {        if  (str != null)  {             str = str.trim ();         }        return  Stringutils.isempty (str);     }    /**     *   Determine if the string is non-null      */    public static boolean  Isnotempty (STRING&NBSP;STR)  {        return !isempty (str);     }} 

This allows you to manipulate the properties configuration file directly using this tool class.
Action example (get the value of an int property and give a default value of 1):

Properties conf = propsutil.loadprops ("config.properties"); int value = Propsutil.getint (conf, "key", 1);

This makes the operation much more convenient.


Java Read Properties configuration file

Related Article

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.