1.Properties class and Properties configuration file
The Properties class inherits from the Hashtable class and implements the Map interface, which also uses a key-value pair to save the property set. But Properties has a special place, that is, its keys and values are all string types.
2. The main method in Properties
(1)load(InputStream inStream)
This method loads the property list into the Properties class object from the file input stream corresponding to the .properties property file. Such as 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 list of properties of the Properties class object to the output stream. Such as the following code:
FileOutputStream oFile = new FileOutputStream(file, "a.properties");
pro.store(oFile, "Comment");
oFile.close ();
If comments is not empty, the first line of the saved property file will be #comments, indicating comment information; if it is empty, there is no comment information.
The comment information is followed by the current save time information of the properties file.
(3)getProperty/setProperty
These two methods are to get and set property information respectively.
3. Code example
The properties file a.properties is as follows:
name=root
pass=liu
key=value
Read a.properties property list, and generate property file b.properties. code show as below:
1 import java.io.BufferedInputStream;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.util.Iterator;
6 import java.util.Properties;
7
8 public class PropertyTest {
9 public static void main(String[] args) {
10 Properties prop = new Properties();
11 try{
12 //Read the properties file a.properties
13 InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
14 prop.load(in); ///Load property list
15 Iterator<String> it=prop.stringPropertyNames().iterator();
16 while(it.hasNext()){
17 String key=it.next();
18 System.out.println(key+":"+prop.getProperty(key));
19 }
20 in.close();
21
22 ///Save the properties to the b.properties file
23 FileOutputStream oFile = new FileOutputStream("b.properties", true);//true means additional open
24 prop.setProperty("phone", "10086");
25 prop.store(oFile, "The New properties file");
26 oFile.close ();
27 }
28 catch(Exception e){
29 System.out.println(e);
30 }
31 }
32 }