I. Properties and properties configuration Files
The properties class inherits from the Hashtable class and implements the map interface, and it also holds the property set in the form of a key-value pair. However, the properties have a special place, that is, its keys and values are string types.
Two. Main methods in the 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. As in the following code:
Properties Pro = new properties (); FileInputStream in = new FileInputStream ("A.properties");p ro.load (in); In.close ();
(2) Store (OutputStream out, String comments)
& nbsp; This method saves the property list of the Properties class object to the output stream. As in the following code:
FileOutputStream ofile = new FileOutputStream (file, "A.properties");p Ro.store (ofile, "Comment"); Ofile.close ();
If comments is not empty, the first row of the saved properties file is #comments, which represents the comment information, and if blank, no comment information.
The comment information is followed by the current save time information for the property file.
(3) Getproperty/setproperty
The two methods are to get and set property information, respectively.
three. Code Examples
Properties The file a.properties is as follows:
Name=rootpass=liukey=value
reads the A.properties property list, with the build properties file b.properties. The code is as follows:
import java.io.bufferedinputstream;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.inputstream; import java.util.iterator;import java.util.properties; public class propertytest { public Static void main (String[] args) { Properties prop = new properties (); try{ // Read the properties file A.properties inputstream in = new BufferedInputStream (New fileinputstream ("A.properties")); prop.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 (); /// Save properties to b.properties file fileoutputstream ofile = new fileoutputstream ("B.properties", true);//true means append open prop.setproperty ("Phone", "10086"); prop.store (ofile, "The new properties file"); ofile.close (); } catch (exception e) { system.out.println (e); } } }
Java Read-write properties configuration file