When I was young, I always liked to write the value of the parameter in the code to die, to run it again, portability is too bad. Since the use of the properties class, it is easier, the code is a little more standardized.
That is, the commonly used, often need to modify the parameters placed in the Xx.properties file, using the properties class provided in Java to read the parameter values in the file, so as to avoid multiple changes in the code parameter values, once and for all.
The properties are actually inherited from the Hashtable, so it is very simple to use, the operation provided mainly:
Load (inputstream): Load Profile Store (outputstream,comment): Writes the newly generated properties object to the file, comment is added descriptive text; GetProperty (name ): Gets the value of a property; SetProperty (Name,value): Sets the value of an attribute, which may not exist beforehand PutProperty (Name,value): Add a property value
Package Propertiestest;import Java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException; Import Java.io.fileoutputstream;import java.io.ioexception;import java.util.properties;/** * * @author WANGJJ * * Jan 7, */public class Testpropertiesclass {public static properties properties; Public Testpropertiesclass (String propertiesfile) throws Exception {properties = new properties (); The properties file is in the format: #comment, argument=value fileinputstream input = new FileInputStream (new file (Propertiesfile) ); Reads the data properties.load (input) from the input stream; }/** * Methods available in Test properties: Get,set,store,put * * @throws IOException * @throws Filenotfoundexcepti On */public void run (String outputproperty) throws FileNotFoundException, IOException {/ /Read Properties String FirstName = Properties.getproperty ("FirstName"); String Hobby = ProperTies.getproperty ("hobby"); System. Out.println ("FirstName:" + firstName); System. Out.println ("hobby:" + hobby); Set existed property Properties.setproperty ("FirstName", "Jing"); FirstName = Properties.getproperty ("FirstName"); System. Out.println ("changed firstName:" + firstName); Set non-existed property Properties.setproperty ("Hello", "World"); System. Out.println ("Hello:" + properties.getproperty ("Hello")); Put non-existed Property Properties.put ("NewProperty", "newvalue"); System. Out.println ("New property:" + Properties.getproperty ("NewProperty")); Properties.store (New FileOutputStream (New File (Outputproperty)), "Outputproperty"); public static void Main (string[] args) throws Exception {String properfile = "Conf/test.properties"; Testpropertiesclass testproperties = new TEstpropertiesclass (Properfile); String outputproperty = "Conf/testnew.properties"; Testproperties.run (Outputproperty); }}
5 minutes to teach you how to learn Java properties