Introduction to the Properties class in Java
Knowledge without it is useless, and it has to be re-learned when it is really used.
The properties class inherits from Hashtable, as follows:
It is mainly used to read the Java configuration file, because many variables in the configuration file often changed, through this class can let the user out of the program itself to modify the relevant variable configuration. In Java, its configuration file is usually a. properties file, formatted as a text file, with the format of "key = value" in the form of the format, #打头的是注释行, properties ignores comments. Allows only key to have no value, and value is set to NULL when there is no value. Java.util.Properties is a mapping of configuration files such as properties. Supports both the Key-value type and the XML type
The properties class implements the map interface, so it is clear that he is using a map to store key-value data, so it is also destined to deposit data is unordered, this point needs attention. The get corresponds to value only by means of key. The configuration file for Key-value is mapped directly to map using the Load method. The Properties property file is a frequently visible and particularly important type of file in Java applications. It is used to configure some information about the application, but this information is generally less data, and it is not necessary to use the database file to save it.
There are several important methods in this class that are summarized as follows:
- GetProperty (String key)that searches for properties in this property list with the specified key. That is, by the parameter key, we get the value of the key.
- load (InputStream instream)to read the list of attributes (key-value pairs) from the input stream. Gets all the key-value pairs in the file by loading the specified file. To search for GetProperty (String key).
- SetProperty (string key, String value) , calls the Hashtable method put. He sets a key-value pair by calling the put method of the base class.
- Store (OutputStream out, String comments)writes the list of attributes (key and element pairs) in this properties table to the output stream, in a format that is appropriate for loading into the properties table using the Load method. In contrast to the load method, the method writes a key-value pair to the specified file.
- Clear ()clears all loaded key-value pairs. This method is provided in the base class.
Java Read the properties file
Here is a common method for groups: implemented by the getResourceAsStream (String name) method of the Java.lang.Class class.
InputStream in = GetClass (). getResourceAsStream ("Resource Name");
or inputstream in = new Bufferedinputstream (new FileInputStream (filepath));
Properties instance
- The Java Virtual machine (JVM) has its own configuration file (system.properties), which gives the system Properties of the JVM as follows
1 Import java.util.Properties; 2 Public class READJVM {3 Public Static void Main (string[] args) {4 Properties pps = system.getproperties (); 5 pps.list (system.out); 6 }7 }
The results of the Operation (Interception section) are as follows:
- Create a new configuration file test.properties
name=jjweight=4444height=3333
1 Public classgetProperties {2 Public Static voidMain (string[] args)throwsFileNotFoundException, IOException {3Properties pps =NewProperties ();4Pps.load (NewFileInputStream ("Test.properties"));5 //The first step is to read the file into the properties class object, because load has a parameter of InputStream, so we can use InputStream Subclass FileInputStream Reads the property file into the properties object and knows the path to prop.properties, we use the FileInputStream (String name) constructor: 6Enumeration enum1 = Pps.propertynames ();//get the name of the configuration file7 while(Enum1.hasmoreelements ()) {8String strkey =(String) enum1.nextelement ();9String strvalue =Pps.getproperty (strkey);TenSystem.out.println (strkey + "=" +strvalue); One } A } -}
The following classes implement common operations for properties
//about operations common to the Properties class Public classtestproperties {//read value by key Public Staticstring Getvaluebykey (String FilePath, String key) {Properties pps=NewProperties (); Try{InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath)); Pps.load (in); String value=Pps.getproperty (key); SYSTEM.OUT.PRINTLN (Key+ " = " +value); returnvalue; }Catch(IOException e) {e.printstacktrace (); return NULL; } } //Read all information about the properties Public Static voidGetallproperties (String FilePath)throwsIOException {Properties pps=NewProperties (); InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath)); Pps.load (in); Enumeration en= Pps.propertynames ();//get the name of the configuration file while(En.hasmoreelements ()) {String strkey=(String) en.nextelement (); String strvalue=Pps.getproperty (strkey); System.out.println (strkey+ "=" +strvalue); } } //Write properties Information Public Static voidWriteProperties (String FilePath, String PKey, String pValue)throwsIOException {Properties pps=NewProperties (); InputStream in=NewFileInputStream (FilePath); //read the list of attributes from the input stream (key and element pairs)pps.load (in); //Call the Hashtable method put. Use the GetProperty method to provide parallelism. //enforces the use of strings for the keys and values of the properties. The return value is the result of the Hashtable call put. OutputStream out =NewFileOutputStream (FilePath); Pps.setproperty (PKey, PValue); //In a format that is appropriate for loading into the Properties table using the Load method,//writes the list of attributes (key and element pairs) in this properties table to the output streamPps.store (out, "Update" + PKey + "name")); } Public Static voidMain (String [] args)throwsioexception{//String value = Getvaluebykey ("test.properties", "name"); //System.out.println (value); //getallproperties ("test.properties");WriteProperties ("Test.properties", "Long", "212"); }}
Result: The data for the file in Test.properties is
#Update long Name#sun Feb 18:17:16 CST 2014name=jjweight=4444long=212height=3333
In addition,Java's properties file needs to be placed under classpath, so that the program can read, about Classpath is actually a Java class or library storage path, in Java engineering, The properties are placed in a class file. In the Web application, the simplest way is to put in the Web-inf\classes directory of the Web application can be placed under other folders, this time need to set the CLASSPATH environment variable, the folder path is added to the CLASSPATH variable, This can also be read. Here, you need to have a deep understanding of classpath, Classpath is not the system deliberately set the system environment variable , web-inf\classes is actually, The class file directory for the VA project is also.
After we know how to read and write a property file, we still have a lot to pay attention to, because both the load and store methods read and write the property stream file according to iso-8859-1 encoding, while the ILatin1 character and some special characters, and for non-Latin1 Characters and some special characters, they are represented as values and elements in a similar escape sequence that is used with character and string literals. So when we are dealing with Chinese, we can not directly modify the property file, the Chinese value is given to the property, but in the Java program through the SetProperty method to give the property the value of Chinese, because this store will convert Chinese into Unicode code, When reading, the system will read the Unicode code printed by the system code, for the Chinese system, usually GBK code, so that Chinese can be displayed normally.
Another form of configuration is XML, which is less common than the previous one.
The configuration file format in the form of XML is roughly the case:
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Properties SYSTEM "Http://java.sun.com/dtd/properties.dtd" > <properties> <comment> hi</comment> <entry key= "foo" >bar</entry> <entry key= "Fu" >baz</entry> </properties>
There is no difference between reading the XML configuration and reading the KV configuration, which is to replace the load with the LoadFromXML method of XML, which is roughly the case:
1 public class Loadsamplexml { 2 public static void Main (String args[]) throws Exception { 3 Properti ES prop = new Properties (); 4 FileInputStream fis = 5 new FileInputStream ("Sampleprops.xml"); 6 prop.loadfromxml (FIS); 7 prop.list (System.out); 8 System.out.println ("\nthe foo property:" + 9 prop.getproperty ("foo")); Ten } 11}
Writing the Properties object in memory to an XML file is similar to the above, which is to change the list method to the Storetoxml method of XML.
The code is roughly like this:
1 Import java.io.IOException; 2 Import Java.io.File; 3 Import Java.io.FileInputStream; 4 Import Java.io.PrintStream; 5 Import java.util.Properties; 6 7 public class Test {8 public static void Main (string[] args) {9 Properties P = new properties (); SetProperty ("id", "Dean"); p.setproperty ("Password", "123456"); try{14 printstream FW = new PrintStream (New File ("E:\\test1.xml")), p.storetoxml (FW, "test"), and a catch (IOException e) { E.printstacktrace () }19 }20}21
Properties class in Java