There is an important class of Properties (Java.util.Properties) in Java, which is mainly used to read the configuration files of Java. Various languages have their own supported configuration files. Many variables in the configuration file are often changed. It is also for the convenience of the user, allowing the user to modify the relevant variable settings without the program itself.
The configuration file corresponding to Properties is a .properties file, and the format is a text file. The format of the content of the file is the "key = value" format. Text annotation information can be annotated with "#". Generally, a pair of key-value is stored on one line.
Second, generate the Properties file
This example uses the Maven project, so the configuration file is generally placed in the resource folder.
Create a test.properties file in the resource folder.
Input inside the file:
test=test
Three, use the Properties class to read the configuration file
package main;
import java.io.InputStream;
import java.util.Properties;
public class ReadFromProperties {
private static final String GLOBAL_CONFIG_FILE = "test.properties"; // enter the file name here
private static Properties globalConf; // reference to the newly created Properties class
public static void main (String [] args) {
try {
globalConf = new Properties (); // Properties object instantiation
// Get the configuration file byte stream through the class loader
InputStream rankConfStream = ReadFromProperties.class.getClassLoader (). getResourceAsStream (GLOBAL_CONFIG_FILE);
// Load the configuration file to Properties class
globalConf.load (rankConfStream);
} the catch (Exception E) {
e.printStackTrace ();
}
// access profile corresponding parameters in the form of the key-value
System.out.println (globalConf.getProperty ( " test "));
}
}
After running the main function, you can see the following output:
test
Process finished with exit code 0
This proves that the program reads the parameter named test in the configuration file (the value is test).