Java read and write Properties configuration file details
- 2020-05-17 05:38:30
- OfStack
Java reads and writes Properties configuration files
1.Properties class and Properties configuration file
The Properties class, which inherits from the Hashtable class and implements the Map interface, also USES a key-value pair to save the property set. The special thing about Properties, though, is that its keys and values are strings.
2. Main methods 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 properties file. 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. 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 properties file will be #comments, indicating the comment information. If it is empty, there is no comment information.
The annotation information is followed by the current save time information for the properties file.
(3)getProperty/setProperty
The 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 the a.properties property list, and generate the 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 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);
}
}
}
Thank you for reading, I hope to help you, thank you for your support of this site!