Java Read and Write properties configuration file
1.Properties class and properties configuration file
The properties class inherits from the Hashtable class and implements the map interface, and also holds the property set in the form of a key-value pair. But properties have a special place, that is, its keys and values are string types.
The main methods in 2.Properties
(1) Load (InputStream instream)
This method can load the 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");
Pro.load (in);
In.close ();
(2) Store (OutputStream out, String comments)
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");
Pro.store (ofile, "Comment");
Ofile.close ();
If the comments is not empty, the first row of the Saved property file is #comments, which indicates the annotation information, and if it is empty there is no annotation 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.
3. code example
The property file A.properties is as follows:
Name=root
Pass=liu
Key=value
Read the A.properties property list, b.properties with the Build property file. 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 Property 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 property to B.properties file FileOutputStream ofile = new FileOutputStream ("B.properties", true);//true indicates append open PROP.S
Etproperty ("Phone", "10086");
Prop.store (Ofile, "The New properties File");
Ofile.close ();
catch (Exception e) {System.out.println (e); }
}
}
Thank you for reading, I hope to help you, thank you for your support for this site!