In-depth analysis of the Properties collection in Java

Hello, friends, hello, I am Meow Shou.

Today I want to share with you some knowledge points that I have learned daily, and communicate with you in the form of words to learn from each other. Although one person can go faster, a group of people can go further.

I am a back-end development enthusiast, and the Java language I come into contact with the most in my daily work, so I try my best to use my spare time to output what I have learned in the form of articles, hoping to help in this way. To more beginners or friends who want to get started, they can also accumulate their own skills, review them, and check for deficiencies.

During the review process, friends, if you think the article is good, please like, collect, and follow it. Sanlian is the best encouragement and support for the author and me on my writing path!

The following is a diagram of the Java collection system architecture. The content of recent issues has been focused on explaining knowledge about this system, so that students can learn Java collection knowledge in a systematic and not fragmented manner.

In Java development, we often need to read some configuration files, such as database configuration files, log configuration files, etc. In Java, we can use the Properties collection to read these configuration files, which is convenient and fast. This article will explain source code analysis, application scenario cases, advantages and disadvantages analysis, class code method introduction, test cases and other aspects of the Properties collection.

This article will introduce the Properties collection in Java, including its basic features, source code analysis, application scenario cases, analysis of advantages and disadvantages, introduction to class code methods, and test cases. Readers will be able to understand the basic concepts and usage of the Properties collection, as well as how to apply it in actual development.

Introduction

Properties is a collection of key-value pairs that can be used to represent a set of configuration information, usually used to read configuration files. In Java, it is a subclass of Hashtable and therefore has all the features of Hashtable. The keys and values in the Properties collection are both string types, and the keys and values are connected with the equal sign “=”.

In Java, we usually use the following method to read Properties files:

Properties prop = new Properties();
InputStream in = new FileInputStream("config.properties");
prop.load(in);

Where config.properties is the name of the configuration file, and the prop.load(in) method loads the key-value pairs in the configuration file into the Properties collection. Next, we can get the value corresponding to the key through the following method:

String value = prop.getProperty("key");

Source code analysis

In the source code of the Properties collection, we can see that it is a subclass of Hashtable, and therefore inherits all methods and characteristics of Hashtable. At the same time, it also implements the Map interface, so you can also use the methods in Map.

The keys and values in the Properties collection are of string type, so it provides some special methods to obtain values of different types. For example, the getProperty(String key, String defaultValue) method can return the default value when the key-value pair cannot be found, and the getProperty(String key) method can obtain the value corresponding to the key.

public String getProperty(String key, String defaultValue) {
    String val = getProperty(key);
    return (val == null) ? defaultValue : val;
}

public synchronized String getProperty(String key) {
    Object oval = super.get(key);
    String sval = (oval instanceof String) ? (String)oval : null;
    return ((sval == null) & amp; & amp; (defaults != null)) ? defaults.getProperty(key) : sval;
}

When reading the Properties file, the Properties collection uses InputStream to read the data and convert it into a character stream.

The specific implementation is as follows:

public synchronized void load(InputStream inStream) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
    while (true) {
        String line = in.readLine();
        if (line == null)
            return;
        if (line.length() > 0) {
            char c = line.charAt(0);
            if ((c != '#') & amp; & amp; (c != '!'))
                while (continueLine(line)) {
                    String nextLine = in.readLine();
                    if (nextLine == null)
                        nextLine = "";
                    String loppedLine = line.substring(0, line.length() - 1);
                    line = loppedLine + nextLine;
                }
            int len = line.length();
            int keyStart;
            for (keyStart = 0; keyStart < len; keyStart + + )
                if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
                    break;
            if (keyStart == len)
                continue;
            char firstChar = line.charAt(keyStart);
            if ((firstChar == '') || (firstChar == '#') || (firstChar == '!')) {
                keyStart + + ;
                if (keyStart == len)
                    continue;
            }
            int separatorIndex = -1;
            for (int i = keyStart; i < len; i + + ) {
                char currentChar = line.charAt(i);
                if (currentChar == '')
                    i + + ;
                else if (separators.indexOf(currentChar) != -1) {
                    separatorIndex = i;
                    break;
                }
            }
            int valueStart = separatorIndex + 1;
            while (valueStart < len) {
                char c = line.charAt(valueStart);
                if (whiteSpaceChars.indexOf(c) == -1)
                    if ((c == '') || (c == '#') || (c == '!'))
                        valueStart + + ;
                    else
                        break;
                valueStart + + ;
            }
            String key = loadConvert(line.substring(keyStart, separatorIndex >= 0 ? separatorIndex : len), true);
            String value = loadConvert(line.substring(valueStart, len), false);
            put(key, value);
        }
    }
}

In this code, the loadConvert(String str, boolean escape) method is used to convert a string into a character stream. The continueLine(String line) method is used to process continuous lines, that is, when the current line ends with a backslash, read the next line and merge it into the current line.

Application scenario cases

The Properties collection is usually used to read configuration files, such as database configuration, log configuration, etc. By saving the configuration information in the Properties collection, we can easily obtain and modify the configuration information.

Here is a simple configuration file example:

db.url=jdbc:mysql:
db.password=654321
db.username=admin

When reading the configuration file, we can use the following code:

Properties prop = new Properties();
InputStream in = new FileInputStream("config/config.properties");
prop.load(in);

String url = prop.getProperty("db.url");
String username = prop.getProperty("db.username");
String password = prop.getProperty("db.password");

Analysis of advantages and disadvantages

The advantages of the Properties collection are:

  • Simple and easy to use: The Properties collection provides simple and easy to use methods to read and write configuration files.

  • Efficient performance: The Properties collection is implemented based on Hashtable, so it has the efficient performance and stability of Hashtable.

  • Readability: The format of the configuration file is key-value pairs, which is easy to read and modify.

The disadvantages of the Properties collection are:

  • Type restrictions: The keys and values in the Properties collection are of string type, so other types of data are not supported.

  • The order is not guaranteed: The storage order of key-value pairs in the Properties collection is uncertain, so the order when reading and writing cannot be guaranteed.

Introduction to class code methods

The following are commonly used methods in the Properties class:

  • getProperty(String key, String defaultValue): Get the value corresponding to the key, and return the default value if the key does not exist.

  • getProperty(String key): Get the value corresponding to the key, and return null if the key does not exist.

  • setProperty(String key, String value): Set key-value pair.

  • load(InputStream in): Load key-value pairs from the input stream.

  • store(OutputStream out, String comments): Write all key-value pairs into the output stream.

The complete Properties class code can be viewed in the official documentation of Java SE.

Test cases

We can write the following test cases to test the reading and writing capabilities of the Properties collection:

Test code demonstration

package com.example.javase.collection;

import java.io.*;
import java.util.Properties;


 * @author ms
 * @date 2023/10/26 18:19
 */
public class PropertiesTest {
    public static void main(String[] args) throws IOException {
        Properties prop = new Properties();

        
        InputStream in = new FileInputStream("config/config.properties");
        prop.load(in);
        in.close();

        
        String url = prop.getProperty("db.url");
        String username = prop.getProperty("db.username");
        String password = prop.getProperty("db.password");
        System.out.println("db.url = " + url);
        System.out.println("db.username = " + username);
        System.out.println("db.password = " + password);

        
        prop.setProperty("db.password", "654321");
        OutputStream out = new FileOutputStream("config/config.properties");
        prop.store(out, null);
        System.out.println("Modified db.password = " + prop.getProperty("db.password"));
        out.close();
    }
}

In this test case, we read a configuration file and output the configuration information. Then, we modified the value of a configuration item and saved it in the configuration file.

The following is the configuration file we used for testing: config.properties

The configuration content is as follows:

db.password=123456
db.url=jdbc:mysql:
db.username=admin

Test results

Based on the above test cases, the local test results are as follows, for reference only. You can also modify the test cases yourself or add more test data or test methods to gain proficiency and deepen your understanding.

Test code analysis

Based on the above test cases, I will give you an in-depth and detailed interpretation of the test code so that more students can understand and deepen their impression.

This is a Java code file, which mainly involves the Properties class in Java. This class is used to read and modify configuration files (.properties files), and has convenient methods for reading and writing configuration properties.

First, the code creates an empty Properties object prop, then uses InputStream to read the property information in the configuration file config/config.properties and loads it into Properties object. Afterwards, get the property value through the getProperty() method and output it to the console. Next, the code modifies the value of the attribute db.password and uses OutputStream to write the modified attribute into the configuration file.

This code example implements the reading and modifying operations of the configuration file and can be used as a reference for examples of processing configuration files in Java.

Full text summary

This article introduces the Properties collection in Java, including its basic features, source code analysis, application scenario cases, analysis of advantages and disadvantages, introduction to class code methods, and test cases. The Properties collection is usually used to read configuration files and has the advantages of simplicity, ease of use, efficient performance, and readability. At the same time, in the actual development process, we need to choose an appropriate solution to use the Properties collection according to the specific situation to avoid problems.

This article introduces the Properties collection in Java, which is a collection of key-value pairs and is usually used to read configuration files. The Properties collection has the advantages of simplicity, ease of use, efficient performance, and readability. At the same time, it also has the disadvantages of type restrictions and the inability to guarantee order. This article deeply analyzes the source code of the Properties collection, introduces its common methods, and gives test cases. In actual development, we need to choose an appropriate solution to use the Properties collection according to the specific situation to avoid problems.

… …

Okay, that’s all my content for this issue. If you have any questions, please leave a message below. See you in the next issue.

… …

There is no order of learning, no amount of knowledge; no matter how big or small the matter is, you should ask for advice with an open mind; among three people, there must be a teacher! ! !

wished for you succeeded! ! !

If you like me, please follow me.

If it is useful to you, please like it.

If you have any questions, please leave a comment and tell me.