Java reads the properties file and loads it into memory

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.