Directly on the code:
Import Java.io.InputStream;
Import java.util.Properties;
public class ReadProperties {
static private String driver = null;
static private String URL = null;
static private String user = null;
static private String password = null;
static{
Loads ();
}
Synchronized static public void loads () {
if (Driver = null | | | url = NULL | | | user = NULL | | password = = NULL) {
InputStream is = ReadProperties.class.getResourceAsStream ("/db.properties");
Properties Dbproperties = new properties ();
try {
Dbproperties.load (IS);
Driver = Dbproperties.getproperty ("Driver"). ToString ();
url = dbproperties.getproperty ("url"). toString ();
user = Dbproperties.getproperty ("user"). toString ();
Password = dbproperties.getproperty ("password"). toString ();
}
catch (Exception e) {
SYSTEM.ERR.PRINTLN ("Cannot read property file." + "Make sure Db.properties is in classpath specified path");
}
}
}
public static String Getdriver () {
if (driver==null)
Loads ();
return driver;
}
public static String GetUrl () {
if (url==null)
Loads ();
return URL;
}
public static String GetUser () {
if (user==null)
Loads ();
return user;
}
public static String GetPassword () {
if (password==null)
Loads ();
return password;
}
}
This method can not only cache the contents of the configuration file, but also to automatically load the contents of the configuration file to memory, the user does not have to consider the process of manual loading, only need to use the place directly call the ReadProperties get method [Example: String URL = Readproperties.getgeturl ()] is ok (because it is a static method without creating an object), so if there is a cache in memory, the function will read the data in memory directly, save time, if no caching system will automatically load