in Java, We often use some values by defining constants, so that we can modify the configuration, such as:
Public Classconstant {public static final String Img_ori_path = "ori/"; public static final String Img_thumb_path = "thumb/"; ......}
so we can use the Constant.img_ori_path Constant.img_thumb_path instead of "thumb/" and so on. Once these paths change, you only need to modify the Constant . Class file, relative time cost is relatively large, and through Java.util.ResourceBundle java.util.Properties Two classes, we can greatly reduce the cost of this time.
ResourceBundle is often used for different languages, that is, internationalization, only for . Properties files, but here we do not discuss internationalization, just use it to achieve the function of properties. If the properties file in your program is only a few configurations, not for multiple languages, you can also use properties , which can be used for various types of files, such as. Properties. Xml.txt.
1. ResourceBundle:
in the project's src/main/resources directory, create a custom systemconfig.properties file. The content in the . Properties file is type Key-value, where we can add the following values:
img.ori.path=ori/
img.thumb.path=thumb/
after use ResourceBundle to fetch the value:
Resoucebundle ResourceBundle = Resourcebundle.getbundle ("Systemconfig"); String Oripath = resourcebundle.getstring ("Img.ori.path"); String Thumbpath = resourcebundle.getstring ("Img.thumb.path");
2. Properties:
Similarly, under the Src/main/resources directory of the project , create a custom systemconfig.txt file with the contents of the file Systemconfig.properties the same, then use the properties to take the value:
Properties Properties = new properties (); FileInputStream FileInputStream = new FileInputStream (Thread.CurrentThread (). Getcontextclassloader (). GetResource (" Systemconfig.txt "). GetPath ());p roperties.load (FileInputStream); String Oripath = Properties.getproperty ("Img.ori.path"); String Thumbpath = Properties.getproperty ("Img.thumb.path");
Of course, the systemconfig.txt here can be placed anywhere in the system, as long as the file path is clear in new FileInputStream () .
in both of these ways, when the path changes, we only need to modify the configuration file, without recompiling the. Class file, saving time for a cup of coffee.
This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1653838
Work accumulation (ii)--using java.util.ResourceBundle and java.util.Properties to achieve constant function