Under the Java.util package, there is a class properties, which is primarily used to read the configuration file in the project (in. Properties end of the file and XML file).
I. Properties structure
The class inheritance structure is as follows:
class extends Hashtable<object,object>
It can be seen from the above that the properties inherit from Hashtable.
Two. Specific cases
Case one: Read the. properties file.
First create a. properties file with the following content:
#网站信息website = Http://www.swiftlet.netauthor = Admindate = 2015
The Java classes are as follows:
ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;Importjava.util.Properties; Public classreadproperties{ Public Static voidMain (string[] args) {File file=NewFile ("C:\\test.properties"); FileInputStream in=NULL; Try{ in=Newfileinputstream (file); } Catch(FileNotFoundException e) {e.printstacktrace (); } Properties P=NewProperties (); Try{p.load (in); } Catch(IOException e) {e.printstacktrace (); } p.list (System.out); }}
The output results are as follows:
Case two: Read the. xml file.
First create an. xml file that reads as follows:
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Properties SYSTEM "Http://java.sun.com/dtd/properties.dtd"><Properties><entryKey= "website">Swiftlet.net</entry><entryKey= "Author">Admin</entry></Properties>
ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;Importjava.util.Properties; Public classreadxml{ Public Static voidMain (string[] args) {File file=NewFile ("C:\\test.xml"); FileInputStream in=NULL; Try{ in=Newfileinputstream (file); } Catch(FileNotFoundException e) {e.printstacktrace (); } Properties P=NewProperties (); Try{p.loadfromxml (in); } Catch(IOException e) {e.printstacktrace (); } p.list (System.out); }}
The output results are as follows:
Three. Frequently asked Questions:
Invalid byte 1 of 1-byte UTF-8 sequence. This exception is caused by:
The XML file that is read is actually GBK or other encoding, while the XML content is used <?xml version= "1.0" encoding= "utf-8"?> specified code utf-8, so the report is abnormal! There are two common types of resolution access:
First: You can change UTF-8 to GBK or GB2312 directly in the XML file
<?xml version= "1.0" encoding= "GB2312"?>
Second: Modify the encoding format of the XML file to Utf-8 and save it again.
Usage of the Properties class