Java read and write Properties configuration file

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 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. Main methods in Properties

(1) load(InputStream inStream)

  This method can load the property list to 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 properties file after saving is first The line 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) The two methods of getProperty/setProperty

  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 property list of a.properties, and generate the property file b.properties. The code is as follows:

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 properties file a.properties
13             InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
14             prop.load(in);     ///加载属性列表
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             ///保存属性到b.properties文件
23             FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打开
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 }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326682629&siteId=291194637