Application of attribute file in Java
We often encounter such problems. For example, we have to use a global variable, such as a variable for TemplateID = FFD4156506-3-2F8CAC7, our general processing method is to define such a global in the program. variable. This is right, but there will be a problem. For example, if this variable is changed, then we must modify it in the program. Especially when our program has been released or has been submitted to the user.
But if we use attribute configuration files to avoid this problem.
Let's take a specific example:
A: Define the TemplateID class:
Import java.io. *;
Import java.util. *;
Public class templateId {
Private static property p;
Private static final templateid pi = new templateId ();
/ **
* Constructor
* /
Public templateId () {
InputStream IS = getClass (). GetResourceceAsStream ("/ templateid.properties"); // get data from the templateId.properties property file
P = new profment ();
Try {
p.Load (IS);
}
Catch (IOException EX) {
EX.PrintStackTrace ();
}
}
/ **
* Get the template ID
* @Return String Template ID
* /
Public static string getTemplateId () {
Return Pi.p.getProperty ("TemplateID"); // The templateID here is the templateID in the templateId.properties property file.
}
Public static void main (string args []) {
System.out.println ("TemplateId =" getTemplateId ()); // Test call
}
}
B: Write the TemplateID.Properties Properties File:
TemplateId.properties: (file suffix is .properties)
TemplateID = FFD4156506-3-2F8CAC7 // does not add quotation, if there are other variables and this similar
Note: The templateID.properties property file is placed in the SRC directory in your project.
If it is called in other classes, you can use it:
TemplateId.getTemplateId ()