Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Properties

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use Properties". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

01. Abstract

The implementation classes of Map are HashMap, LinkedHashMap, TreeMap, IdentityHashMap, WeakHashMap, Hashtable, Properties, and so on.

02. Brief introduction

The Properties class is a very important class in the java toolkit. For example, in actual development, some variables can be hard-written directly into the custom java enumerated class.

But some variables, in the test environment, pre-production environment, production environment, variables need to take different values, at this time, we can use the properties file to load the configuration information needed by the program, in order to achieve a line of code, multiple environments can run the effect!

The most common ones are JDBC data source configuration files, where properties files are suffixed with .properties, and the contents of the files are written in the format of key = value, with variable names on the left and variable values on the right, and annotated with #, such as creating a new jdbc.properties file, as follows:

The Properties class is the intermediate bridge between the properties file and the program. Whether reading information from the properties file or writing information to the properties file, it is through the Properties class.

Well, after so much nagging, let's go back to the protagonist Properties in this article!

As you can see from the collection Map architecture diagram, Properties inherits from Hashtable and represents a persistent map collection. The list of properties exists in the form of key-value, and the Properties class is defined as follows:

Public class Properties extends Hashtable {. }

In addition to inheriting the methods defined in Hashtable, Properties also defines the following common methods, as shown in the figure:

Introduction of common methods

Set method (add modified element)

The set method adds the specified key and value pairs to the map. When adding elements, the put method of Hashtable is called. Unlike Hashtable, key and value are both strings.

Open the setProperty method of Properties. The source code is as follows:

Public synchronized Object setProperty (String key, String value) {/ / calls the put method return put (key, value) of the parent class Hashtable;}

The method is tested as follows:

Public static void main (String [] args) {Properties properties = new Properties (); properties.setProperty ("name1", "Zhang San"); properties.setProperty ("name2", "Zhang Si"); properties.setProperty ("name3", "Zhang Wu"); System.out.println (properties.toString ());}

Output result:

{name3= Zhang Wu, name2= Zhang Si, name1= Zhang San}

Get method (search for specified elements)

The get method returns the corresponding value according to the specified key value. The first step is to call the get method of Hashtable. If there is a return value, it returns directly; if there is no return value, but the defaults variable is passed in during initialization, from the defaults variable, that is, Properties, to search for whether there is a variable for it, and if so, return the element value.

Open the getProperty method of Properties. The source code is as follows:

Public String getProperty (String key) {/ / calls the get method of the parent class Hashtable Object oval = super.get (key); String sval = (oval instanceof String)? (String) oval: null; / / determines that the variable is not empty return ((sval = = null) & & (defaults! = null)? Defaults.getProperty (key): sval;}

Check the variable defaults. The source code is as follows:

Public class Properties extends Hashtable {protected Properties defaults;}

When will this variable be assigned? open the source code as follows:

Public Properties (Properties defaults) {this.defaults = defaults;}

You can find that during the initialization phase of the Properties constructor, if you give a custom defaults, when the get method that calls Hashtable does not search for the element value, and the defaults is not equal to null, then you will further search for the element value in the defaults.

The method is tested as follows:

Public static void main (String [] args) {Properties properties = newProperties (); properties.setProperty ("name1", "Zhang San"); properties.setProperty ("name2", "Zhang Si"); properties.setProperty ("name3", "Zhang Wu"); / / initialize properties into newProperties Properties newProperties = newProperties (properties); newProperties.setProperty ("name4", "Li San") / / query the value System.out.println of name1 in key ("query result:" + properties.getProperty ("name1"));}

Output result:

Query result through key: Zhang San

Load method (load configuration file)

The load method means that the properties file is loaded as an input stream, and the key and value pairs are extracted, and the key-value pair elements are added to the map.

Open the load method of Properties. The source code is as follows:

Public synchronized void load (InputStream inStream) throws IOException {/ / read file stream load0 (new LineReader (inStream));}

Load0 method. The source code is as follows:

Private void load0 (LineReader lr) throws IOException {char [] convtBuf = new char [1024]; int limit; int keyLen; int valueStart; char c; boolean hasSep; boolean precedingBackslash; / / read while ((limit = lr.readLine ()) > = 0) {c = 0; keyLen = 0; valueStart = limit; hasSep = false; precedingBackslash = false / / determine the length of key while (keyLen < limit) {c = lr.lineBuf [keyLen]; if ((c = ='='| | c = =':') & &! precedingBackslash) {valueStart = keyLen + 1; hasSep = true; break } else if ((c = =''| | c = ='\ t'| | c = ='\ f') & &! precedingBackslash) {valueStart = keyLen + 1; break;} if (c = ='\\') {precedingBackslash =! precedingBackslash;} else {precedingBackslash = false } keyLen++;} / / get the starting position of the value while (valueStart < limit) {c = lr.lineBuf [valueStart] If (c! ='& & c! ='\ t'& & c! ='\ f') {if (! hasSep & & (c = ='| c = =':')) {hasSep = true;} else {break }} valueStart++;} / / get the key and value parameters in the file String key = loadConvert (lr.lineBuf, 0, keyLen, convtBuf); String value = loadConvert (lr.lineBuf, valueStart, limit-valueStart, convtBuf); / / call the put method of Hashtable to add the key value to put (key, value) in map;}}

All right, let's create a new custom.properties configuration file under the src/recources directory, as follows:

# define a variable name and value userName= Li San userPwd=123456 userAge=18 userGender= male userEmail=123@123.com

The method is tested as follows:

Public class TestProperties {public static void main (String [] args) throws Exception {/ / initialize Properties Properties prop = new Properties (); / / load the configuration file InputStream in = TestProperties .class.getClassLoader (). GetResourceAsStream ("custom.properties"); / / read the configuration file, specify the encoding format, and avoid reading prop.load (new InputStreamReader (in, "UTF-8")) / / output the content to the console prop.list (System.out);}}

Output result:

UserPwd=123456

UserEmail=123@123.com

UserAge=18

UserName= Li San

UserGender= male

PropertyNames method (read all information)

The propertyNames method, which reads all the information from the Properties, essentially creates a new Hashtable object, then copies the data from the original Hashtable to the new Hashtable, and returns all the key in the map.

Open the propertyNames method of Properties. The source code is as follows:

Public Enumeration propertyNames () {Hashtable h = new Hashtable (); / / add the original map to the new Hashtable enumerate (h); / / return all key elements in Hashtable return h.keys ();}

Enumerate method. The source code is as follows:

Private synchronized void enumerate (Hashtable h) {/ / determine whether there is an initialized configuration file if (defaults! = null) {defaults.enumerate (h);} / / add the data from the original Hashtable to the new Hashtable for (Enumeration e = keys (); e.hasMoreElements ();) {String key = (String) e.nextElement (); h.put (key, get (key)) }}

The method is tested as follows:

Public static void main (String [] args) throws Exception {/ / initialize Properties Properties prop = new Properties (); / / load the configuration file InputStream in = TestProperties.class.getClassLoader () .getResourceAsStream ("custom.properties"); / / read the configuration file, specify read encoding UTF-8, prevent content garbled prop.load (new InputStreamReader (in, "UTF-8")) / / get all key elements in Properties Enumeration enProp = prop.propertyNames (); while (enProp.hasMoreElements ()) {String key = (String) enProp.nextElement (); String value = prop.getProperty (key); System.out.println (key + "=" + value);}}

The output is as follows:

UserPwd=123456

UserEmail=123@123.com

UserAge=18

UserName= Li San

UserGender= male

Summary

Properties inherits from Hashtable, and most methods are reused for Hashtable, for example, get, put, remove, and clear methods. * * unlike Hashtable, key and value in Properties are strings. * * if you need to obtain all the contents of properties, you can first obtain all key elements in map through iterator or propertyNames method, and then traverse to get key and value.

It should be noted that the setProperty and load methods in Properties all add synchronized synchronization locks to control thread synchronization.

03. How properties files are loaded

In the actual development, we often encounter the problem that the path of reading the configuration file can not be found, or the contents of the read file are garbled. Here is a brief introduction to several common loading methods of properties files.

The way properties loads files can be roughly divided into two categories: the first is to use java.util.Properties 's load method to load the file stream; the second is to use the java.util.ResourceBundle class to get the contents of the file.

Under the src/recources directory, create a new custom.properties configuration file with the file encoding format of UTF-8. The content still takes the test as an example, and each load mode is as follows!

Load the file through the file path

This kind of method loads the file, mainly calls the load method of Properties, obtains the file path, reads the file and loads the file in the form of stream.

The methods are as follows:

Properties prop = new Properties (); / / get the file absolute path String filePath = "/ coding/java/src/resources/custom.properties"; / / load the configuration file InputStream in = new FileInputStream (new File (filePath)); / / read the configuration file prop.load (new InputStreamReader (in, "UTF-8")); System.out.println ("userName:" + prop.getProperty ("userName"))

Output result:

UserName: Li San

Through the getResourceAsStream method of the current class loader

This kind of method loads the file and also calls the load method of Properties. The difference is that the file path is obtained through the class loader. If the current file is in the src/resources directory, just pass in the file name.

The methods are as follows:

Properties prop = new Properties (); / / load the configuration file InputStream in = TestProperties.class.getClassLoader () .getResourceAsStream ("custom.properties"); / / read the configuration file prop.load (new InputStreamReader (in, "UTF-8"); System.out.println ("userName:" + prop.getProperty ("userName"))

Output result:

UserName: Li San

Get using the getSystemResourceAsStream method of the ClassLoader class

Similar to the above, the file stream is also obtained through the class loader as follows:

Properties prop = new Properties (); / / load the configuration file InputStream in = ClassLoader.getSystemResourceAsStream ("custom.properties"); / / read the configuration file prop.load (new InputStreamReader (in, "UTF-8"); System.out.println ("userName:" + prop.getProperty ("userName"))

Output result:

UserName: Li San

Use the ResourceBundle class to load a file

The ResourceBundle class loads the file, unlike Properties, ResourceBundle does not need to add a .properties suffix to get the properties file, just the file name.

ResourceBundle reads the original attribute file according to the iso8859 coding format. If it reads Chinese content, it needs transcoding processing.

The methods are as follows:

/ / load custom configuration file without adding `.properties` suffix ResourceBundle resource = ResourceBundle.getBundle ("custom"); / / transcode to solve the garbled problem of reading Chinese content String value = new String ("userName"). GetBytes ("ISO-8859-1"), "UTF-8"); System.out.println ("userName:" + value)

Output result:

UserName: Li San

This is the end of "how to use Properties". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 221

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report