Java learning notes 41 (Properties class), learning notes properties
Properties enables persistent storage of collection data
It is an implementation class of the map interface. You can use the map class method,
But there is a difference: it does not have a generic type, specifying the key type as a string
This set will be frequently used in future development, such as connecting to a database.
This section briefly introduces the basic usage. The detailed usage is described later.
Storage obtains key-value pairs:
package demo;import java.util.Properties;import java.util.Set;public class PropertiesDemo { public static void main(String[] args) { function(); } public static void function(){ Properties pro1 = new Properties(); pro1.setProperty("a", "1"); pro1.setProperty("b", "2"); pro1.setProperty("c", "3"); System.out.println(pro1); String value = pro1.getProperty("c"); System.out.println(value); Set<String> set = pro1.stringPropertyNames(); for(String key:set){ System.out.println(key+"="+pro1.getProperty(key)); } }}
Collection Methods:
Load Method:
Load the key-value pairs in the file to the Collection
Create a new text file with the suffix changed to. properties and write the key-Value Pair
package demo;import java.io.FileReader;import java.io.IOException;import java.util.Properties;public class PropertiesDemo { public static void main(String[] args) throws IOException { function(); } public static void function() throws IOException{ Properties pro1 = new Properties(); FileReader fr1 = new FileReader("d:\\pro.properties"); pro1.load(fr1); fr1.close(); System.out.println(pro1); }}
Store Method:
Write key-value pairs
Package demo; import java. io. fileWriter; import java. io. IOException; import java. util. properties; public class PropertiesDemo {public static void main (String [] args) throws IOException {function ();} public static void function () throws IOException {Properties pro1 = new Properties (); pro1.setProperty ("name", "zhangsan"); pro1.setProperty ("age", "18"); pro1.setProperty ("email ", "123456@qq.com"); FileWriter fWriter = new FileWriter ("d: \. properties "); pro1.store (fWriter," the reason "); // the second parameter is often omitted by fWriter. close ();}}