Dynamic loading of properties files in Java without the need to restart application solutions
In a Java project, if you need to use a file of. Properties type to store the media as some configuration information, the. properties file is usually placed in the SRC directory, and most of the code is written like this:
Properties prop = new properties ();
InputStream is = CommonUtils.class.getClassLoader (). getResourceAsStream ("config.properties"); Suppose the current method is under the Commonutils class
Prop.load (IS);
After the system is started, Config.properties in the Key-value information can be obtained, but one day, you want to change the config.properties in the relevant configuration, but can not restart the application, you will find that the Config.properties file has been modified, why read The information is still the original.
After Google found that the original use:
CommonUtils.class.getClassLoader (). getResourceAsStream ("Config.properties")
This load method loads the Config.properties file into memory, fetching the file information directly from memory the next time it needs to be read, rather than reading it again.
Now that the above method caches the file information, I just need to change the way the input stream of the file is fetched.
Change it to the following way:
Properties prop = new properties ();
String path = CommonUtils.class.getClassLoader (). GetResource ("Config.properties"). GetPath ();
InputStream is = new FileInputStream (path);
Prop.load (IS);
Or
String Dirpath = Thread.CurrentThread (). Getcontextclassloader (). GetResource (""). GetPath ();// Gets the parent directory where the config.properties file resides
File File = new file (Dirpath, "config.properties");
Note: In the process of using a problem, Mark---"I again static method with read properties (using a method to read without restarting), but after modifying the properties file, the discovery is not effective, and later found that the reason for static. (about static you can Baidu to understand)
Http://www.myexception.cn/internet/1484938.html