Java Read and Write Properties Configuration Files
1.Properties class and Properties configuration file
The Properties class inherits from the Hashtable class and implements the Map interface. It also uses a key-value pair form to save the property set. However, Properties has a special feature, that is, its keys and values are both string types.
2. The 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. As shown 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 Properties class objects into the output stream. As shown in the following code:
FileOutputStream oFile = new FileOutputStream(file, "a.properties");pro.store(oFile, "Comment");oFile.close();
If comments are not empty, the first line of the saved property file will be #comments, indicating comment information; if empty, there will be no comment information.
The comment information is followed by the current storage time information of the attribute file.
(3) getProperty/setProperty
These two methods are to obtain and set attribute information respectively.
3. Code examples
The properties file a.properties are as follows:
name=root
pass=liu
key=value
Read the a.properties property list, and generate the property 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 property file a.properties InputStream in = new BufferedInputStream (new FileInputStream("a.properties")); prop.load(in); ///Load the 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 the property to the b.properties file FileOutputStream oFile = new FileOutputStream("b.properties", true);//true means to add prop.setProperty("phone", "10086"); prop.store(oFile, "The New properties file"); oFile.close(); } catch(Exception e){ System.out.println(e); } } }Thank you for reading, I hope it can help you. Thank you for your support for this site!