|
Package com. test. demo;
Import java. util. Properties;
Import java. io. InputStream;
Import java. io. IOException;
/**
* Example of reading the Properties File
* File: TestProperties. java
*/
Public final class TestProperties {
Private static String param1;
Private static String param2;
Private static String param3;
Private static String param4;
/**
* The Path Name of the preceding configuration file is easily overlooked,
* That is, when you use Object. class. getClassLoader (). get,
* Yes, you do not need to add "/".
* But it won't work when getClassLoader () is not needed. Why?
* Because the configuration file is placed under the src of the project, "/" must be added during object loading.
* If you copy the configuration file to the same package as the class, you do not need to add it,
* If the configuration file is read in the following way:
*/
Static {
Properties prop = new Properties ();
// InputStream in = Object. class. getResourceAsStream ("/test. properties ");
// File under src
// InputStream in = TestProperties. class. getClassLoader (). getResourceAsStream ("jdbc. properties ");
// File under src
InputStream in = TestProperties. class. getResourceAsStream ("jdbc. properties ");
// The file is in the same package
Try {
Prop. load (in );
Param1 = prop. getProperty ("mysql. driverClassName"). trim ();
Param2 = prop. getProperty ("mysql. url"). trim ();
Param3 = prop. getProperty ("mysql. username"). trim ();
Param4 = prop. getProperty ("mysql. password"). trim ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
/**
* The private constructor does not need to create objects.
*/
Private TestProperties (){
}
Public static String getParam1 (){
Return param1;
}
Public static String getParam2 (){
Return param2;
}
Public static String getParam3 (){
Return param3;
}
Public static String getParam4 (){
Return param4;
}
Public static void main (String args []) {
System. out. println (getParam1 ());
System. out. println (getParam2 ());
System. out. println (getParam3 ());
System. out. println (getParam4 ());
}
}
|