Application of Property Files in Java
We often encounter this problem, for example, we want to use a global variable, for example, to use a variable such as templateid = FFD4156506-3-2F8CAC7, the general solution is to define such a global variable in the program. This is true, but there will be a problem. For example, if the variable changes, we must modify it in the program. This is especially troublesome when our programs have been released or submitted to users.
However, we can avoid this problem if we use the property configuration file.
The following is a specific example:
A: defines the templateid class:
Import java. Io .*;
Import java. util .*;
Public class templateid {
Private Static Properties P;
Private Static final templateid Pi = new templateid ();
/**
* Constructor
*/
Public templateid (){
Inputstream is = getclass (). getresourceasstream ("/templateid. properties"); // obtain data from the templateid. properties property File
P = new properties ();
Try {
P. Load (is );
}
Catch (ioexception ex ){
Ex. printstacktrace ();
}
}
/**
* Obtain 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 property file:
Templateid. properties: (the file suffix is. properties)
Templateid = FFD4156506-3-2F8CAC7 // No quotation marks, if there are other variable writes similar to this
Note: The templateid. properties attribute file is stored in the src directory of your project.
If it is called in other classes, it can be used as follows:
Templateid. gettemplateid ()