Learn about the properties of the Java configuration file

Source: Internet
Author: User

In early Java development, common *.properties files store some configuration information. The information in its files is primarily stored in a key=value manner, and is widely used in the early days. And then with the extensive use of XML, its position is gradually replaced, but there are still some frameworks such as log4j in use it. Recently, I used it when I was making my own gadgets, and I had a bit of a deeper understanding to share.

When Java is operating on a *.properties file, it actually scans the document on a progressive basis via IO, and then stores the non-annotated portions of the text in a Properties object. The Properties actually inherit the Hashtable and implement the map interface. It can be understood that it is a further encapsulation of the hashmap. When stored in the properties, you can perform a series of operations on the properties, where the data is stored in memory. Finally, when you need to save the data, you write all the key values in the properties to the file again. The JDK provides a series of APIs for the operation of the properties file. is a tool class, to achieve the properties of the file additions and deletions to check the function.

  1 package com.sean.file.properties;  2 3 Import Java.io.File;  4 Import Java.io.FileOutputStream;  5 Import java.io.IOException;  6 Import Java.io.InputStreamReader;  7 Import Java.io.OutputStreamWriter;  8 Import java.io.UnsupportedEncodingException; 9 Import java.util.Enumeration; Ten import Java.util.HashMap; Import Java.util.Map; Import java.util.Properties;   /** * Java Operation Properties of the tool class 15 * Implementation function: 16 * 1, properties file additions and deletions check function 17 * 2, solve the problem of reading and writing Chinese garbled * @author Sean 19 * 20 * * * public class Propertiesutil {/** * Properties address value, no need to add root tag "/" +/-Private String s rc = ""; Private InputStreamReader InputStream = null; OutputStreamWriter private outputstream = null; Private String encode= "Utf-8"; Public properties Properties;      31 32/** 33 * Default Constructor * */Public Propertiesutil () {36} 37 38/** 39 * Constructor 40     * * * @param src Incoming Properties address value, do not need to add root tag "/" 42 * * Public propertiesutil (String src) {this.src = src; 45} 46 47 48/** 49 * Construction function, providing the setting encoding mode of * @param src incoming Properties address value, do not need to add root tag "/" Wuyi * @param encode incoming corresponding encoding mode, default is Utf-8 52 *     /Propertiesutil (string src, string encode) {This.encode = encode; 56 } 57 58/** 59 * Load Properties File * @author Sean * @date 2015-6-5 * @return return read Properti Es Object * * * public Properties Load () {Src.trim (). Equals ("")) {$ throw new Runtimeexc Eption ("The path of the Properties File is need"); (*) * try {
           FileInputStream fis = new FileInputStream (SRC);Inputstream=new InputStreamReader (FIS/*classloader.getsystemresourceasstream (SRC) */, encode); (Unsupportedencodingexception E1) {e1.printstacktrace (); proper Ties=new Properties (); Properties.load try {inputstream); catch (IOException e) {e.prints Tacktrace (); ~ +} + return properties; 80} 81 82/** 83 * Write configuration to File * * @author Sean * @date 2015-6-5 * @throws Exception * * * Write2file () throws exception{89//Get file output stream outputstream=new Outputstrea Mwriter (New FileOutputStream (src /* Classloader.getsystemresource (SRC). Touri () */)), encode); Properties.store (OutputStream, NULL); Close (); 93} 94 95 96/** 97 * Get values by keyword 98 * @author Sean * @date 2015-6-5100 * @param ke Y need to get the keyword 101 * @return return the corresponding string, if none, return null102 */103 public string Getvaluebykey (string key) {104 Properties=load (); =properties.getproperty String Val-Key.trim (); 106 close (); 107 return VAL;108 109}110 111/**112 * Get values by keyword 113 * @author Sean114 * @date 2015-6-5115 * @param key required to obtain the keyword DefaultValue * @param the value returned if the corresponding keyword is not found 117 * @return return the found string 118 */119 public string Getvaluebykey (string key, String defaultvalue) {properties=load (); 121 String Val =properties.getproperty (Key.trim (), Defaultvalue.trim ()); 122 close (); 123 return val;124}125 126/**127 * off input/output stream * @author Sean129 * @date 2015-6-5130 */131 public void Close () {try {133 if (inputstream!=null) {InputStream . Close ();} 134 if (outputstream!=null) {outputstream.close ();} 135} catch (IOException e) {136 e.printstacktrace (); 137}138}139 140/**141 * Get all values of properties 142 * @author Sean143 * @date 2015-6-5144 * @return return properties of key value pairs 145 */146 public map<string,string> getallproperties () {147 properties=load (); 148 Map<string,strin G> map=new hashmap<string,string> (); 149//Get all key values of enumeration Enumeration=properties.propertyn Ames (); 151 while (enumeration.hasmoreelements ()) {string key= (String) enumeration.nextelement (); 153 String Value=getvaluebykey (key); 154 Map.put (key, value); 155}156 Close (); 157 return map;158}159 160/**161 * Write new key value to properties 162 * @author Sean163 * @date 2015-6-5164 * @param key corresponding keys 165 * @param value corresponds to 166 */167 public void Addproperties (String key,string value) {168 properties=load (); 169 Properties.put (key, value); 1 try {171 write2file (); 172} catch (Exception e) {173 e.printstacktrace (); 174 }175}176 177/**178 * Add all values in Map 179 * @author Sean180 * @date 2015-6-5181 * @param Map corresponding key-value pair set 182 */183 public void Addallproperties (map<string,string> Map) {184 properties=load () ; 185 Properties.putall (map); 186 try {187 write2file (); 188} catch (Exception e) {189 E.printstacktrace (); runtimeexception throw new ("Write fail"); 191}192}193 194 /**195 * Update Profile 196 * @author Sean197 * 2015-6-5198 * @param key needs to be updated value 199 * @param value Corresponds to a value of 200 */201 public void Update (String key,string value) {202 properties=load (); 203 if (!properties.containskey (key)) {2 RuntimeException throw new ("Not such key") 205}206 properties.setproperty (key, value); 207 try {208 write2file (); 209} catch (Exception e) {e.printstacktrace (); 211 throw new RuntimeException ("Write fail"); 212}213}214 215/**216 * Delete a key value pair 217 * @aut Hor Sean218 * 2015-6-5219 * key value corresponding to @param key-*/221 public void DeleteKey (String key) {222 Properties=load (); 223 if (!properties.containskey (key)) {224 throw new runtimeexception ("Not such key"); 225}226 Properties.remove (key); 227 try {228 write2file (); 229} catch (Excepti On e) {e.printstacktrace (); 231 throw new RuntimeException ("Write fail"); 232}233} 234 235/**236 * Set Path value 237 * @author Sean238 * @date 2015-6-5239 * @param src corresponding file value */241 public void SETSRC (String src) {242 this.src = src;243}244}

Basically, the common use of the properties of this tool class can be done. It is worth noting that because the program ignores the contents of the comment when it scans the properties, and when the content is re-written into the text, the program will only write the values in the properties, which will comment on the missing case. In this case, the solution for someone on the net is to create a new class that inherits the properties, and then put the information that the program reads, including comments, into Linkedhashmap so that the comments can be saved.

However, the same functionality can be achieved through the open source project Commons-configuration on Apache. Commons-configuration is primarily an API that implements configuration file operations such as XML, properties, and so on. It also enables the operation of the properties, while at the same time, the annotations in the file can be saved during operation.

When using Commons-configuration for the properties of the file operation, not only need to import the Commons-configuration.jar package, but also need to import several other dependent packages to implement.

The following is a demo that instinctively uses the API provided by Commons-configuration to perform the properties operation

Package Com.sean;import Java.io.file;import Java.io.filenotfoundexception;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.outputstream;import Java.io.outputstreamwriter;import Java.net.urisyntaxexception;import Org.apache.commons.configuration.configuration;import Org.apache.commons.configuration.configurationexception;import        Org.apache.commons.configuration.propertiesconfiguration;public class Propertiesutil {private String src= "";        Private Propertiesconfiguration Pcf=null;        Private String encode= "Utf-8";        /** * Default constructor */Public Propertiesutil () {}; /** * Parameter constructor * @param src incoming corresponding file address */public propertiesutil (String src) {This            . src=src;            try {pcf=new propertiesconfiguration (src);            } catch (ConfigurationException e) {e.printstacktrace ();        } pcf.setencoding (encode);                   }     /** * Gets the value of a specific key * @param key corresponding to the value * @return return the corresponding value value, cannot find the return null;            */Public String GetValue (string key) {string s=pcf.getstring (key);        return s; }/** * Update the corresponding value * @param key corresponding to the keyword * @param value corresponding to the values */public void Updatevalue (String key,string value) {if (!pcf.containskey (key)) {throw new Runtimeexcep                tion ("Not such key"); } try {Pcf.save (New FileOutputStream (Classloader.getsystemresource (SRC). Touri (                )), "Utf-8");                } catch (ConfigurationException e) {e.printstacktrace ();                } catch (FileNotFoundException e) {e.printstacktrace ();                } catch (URISyntaxException e) {e.printstacktrace (); }}/** * Add key value pairs * @param keY keyword * @param value values */public void AddValue (String key,string value) {PCF.A                Ddproperty (key, value);                try {pcf.save (new FileOutputStream (New File (Classloader.getsystemresource (SRC). Touri ())), "Utf-8");                    } catch (ConfigurationException e) {//TODO auto-generated catch block                E.printstacktrace (); } catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstackt                Race (); } catch (URISyntaxException e) {//TODO auto-generated catch block E.printstacktrac                E ();                }}/** * Delete keyword * @param key keyword */public void Delvalue (String key) {                Pcf.clearproperty (key); try {pcf.save (New FileOutputStream (Classloader.getsystemresource (SRC). TourI ())), "Utf-8"); } catch (ConfigurationException e) {//TODO auto-generated catch block E.printstack                Trace (); } catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstackt                Race (); } catch (URISyntaxException e) {//TODO auto-generated catch block E.printstacktrac                E (); }        }                }

As you can see, the API provided by Commons-configuration is much simpler to operate. However, because Commons-configuration is a foreign open source project, its support for Chinese has some problems. Although the ability to set character encoding is provided in the API, there is no good solution to the problem of Chinese. In contrast, native APIs are relatively simple to implement.

Finally, to summarize, on the operation of the properties, JDK and commons-configuration have provided better support, regarding the use of the original survival is the framework, should be based on specific conditions. But we should keep the principle in the case of not repeating the wheel.

Learn about the properties of the Java 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.