Use of the Properties class

Properties class

1 Introduction

Properties inherits from Hashtable. Represents a persistent set of properties. Each key and its corresponding value in the property list is a string , where the key-value pair is separated by an equal sign. Properties can be saved in or loaded from a stream. Each key and its corresponding value in the property list is a string. The Properties class is thread-safe: multiple threads can share a single Properties object without external synchronization

The file type is usually *.properties, format: key=value

2. Important methods of the Properties class

The Properties  class exists in the cell Java.util, which inherits from Hashtable

1. getProperty(String key) Searches this property list for a property with the specified key. That is, through the parameter key, the value corresponding to the key is obtained.
2. load ( InputStream inStream ) , which reads a list of attributes (key and element pairs) from the input stream. Get the file by loading the specified file (such as the test.properties file above)
All key-value pairs in the file. For getProperty (String key) to search.
3. setProperty (String key, String value), call the method put of Hashtable. It sets the key-value pair by calling the put method of the base class.
4. store ( OutputStream out, String comments) , in a format suitable for loading into the Properties table using the load method, a list of properties (keys and elements) in this Properties table
right) to write to the output stream. In contrast to the load method, this method writes key-value pairs to the specified file.
5. clear() , clears all loaded key-value pairs. This method is provided in the base class.

Properties defines the following methods:

serial number

Method description

1

String getProperty(String key)
 
Searches this property list for a property with the specified key.

2

String getProperty(String key, String defaultProperty)
Searches the property list for the property with the specified key.

3

void list(PrintStream streamOut) prints
 the property list to the specified output stream.

4

void list(PrintWriter streamOut)
outputs the property list to the specified output stream.

5

void load(InputStream streamIn) throws IOException
 Reads a list of properties (key and element pairs) from the input stream.

6

Enumeration propertyNames( )
reads a list of properties (key and element pairs) from the input character stream in a simple line-oriented format.

7

Object setProperty(String key, String value)
 calls the method put of Hashtable.

8

void store(OutputStream streamOut, String description)
 Writes the list of properties (key and element pairs) in this Properties table to the output stream in a format suitable for loading into the Properties table using the load(InputStream) method.

3. Use of Properties class

a) Load external properties files to decouple configuration and java code
public class SystemResourceUtil {
	private static Logger logger = LoggerFactory.getLogger(SystemResourceUtil.class);
	/**
	 * Used to store the loaded local properties file
	 */
	private final static Map<String, Properties> propertiesMap = new HashMap<String, Properties>();

        /**
	 * Get local resource files
	 */
	public final static Properties getPropertisByName(String propertiesName) {
		Properties p = propertiesMap.get(propertiesName);
		// read from local does not exist in memory
		if (null == p) {
			p = FileUtil.getProperties(propertiesName);
			propertiesMap.put(propertiesName, p);
		}

		return p;
	}

        /**
	 * Get configuration file public method
	 */
	public static Properties getProperties(String fileName) {
		// FileUtil fileUtil = new FileUtil();
		Properties p = new Properties();
		// InputStream in = FileUtil.class.getResourceAsStream(fileName);
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(fileName);
		if (in == null) {
			return p;
		}
		try {
			p.load(in);
		} catch (IOException e) {
			logger.error("-- Failed to read configuration file", e);
		} finally {
			StreamUtil.closeStream(in);
		}
		return p;
	}

b) Create a properties object and set the property value

        public void initProducer() {
		Properties p = new Properties();
		p.setProperty(MQCPConstant.PRODUCER_ID, producerId);
		MQCPProducer producer = null;
		try {
			// Get the MQCPProducer instance, the producer is a single instance
			producer = MQCPFactory.createProducer(p);
			// start the service
			producer.start();
		} catch (MQCPException e) {
			return;
		}	
		PRODUCER_REGISTER.put(producerId, producer);
	}

4. 3 ways and differences to get file stream

方式1:InputStream in = this.getClass().getResourceAsStream("/cfs.properties");

方式2:InputStream in = this.getClass().getClassLoader().getResourceAsStream("cfs.properties");

方式3:InputStream in =Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE);

Arguments in mode 1 can start with / or directly by name. Starting with / indicates the absolute path, which starts from the root path of the ClassPath . If there is no / direct name, it indicates the relative path, then start to find the file in the package where the class is located. Mode 1 essentially calls Mode 2 method, the processing logic is to remove the / if there is a /, otherwise put the package name + parameter directly in front of

Mode 2 starts the search from the root path of c ClassPath by default, and cannot start with /

Method 3 also obtains the absolute URI path of the current ClassPath . The class we defined is loaded first, and the system is loaded if it cannot be loaded. Such a requirement cannot be satisfied by the default parent delegation loading mechanism of the system. You can specify the corresponding ClassLoader for the current thread, and then use the get method to obtain it. better versatility

Among them, bin is the classpath of this project. All compiled .class files from Java source files are copied into this directory.

Note: The following acquisitions are the same

  com.explorers.Test.class.getResourceAsStream("abc.jpg")=com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")=ClassLoader.getResourceAsStream("com/explorers/abc.jpg")


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325721683&siteId=291194637