Java learning notes 41 (Properties class)

Properties can be used for persistent storage of collection data

It is an implementation class of the map interface. You can use the methods of the map class,

However, there is a difference: it has no generics and specifies that the key type is a string

 

This collection will be frequently used in future development, such as connecting to databases, etc

Here is a brief introduction to the basic usage. The detailed usage will be introduced later

 

Store get key value pair:

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));
        }
        
    }
}

 

 

Set specific methods:

load method:

Load the key value pairs in the file into the collection

Create a new text file, change the suffix 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 pair

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:\\a.properties");
        pro1.store(fWriter, "the reason");//The second parameter is often omitted
        fWriter.close();
    }
}

Tags: Java

Posted on Fri, 01 May 2020 09:31:57 -0700 by linuxdoniv