http://blog.csdn.net/hopestar2/article/details/6372883
A variety of configuration files are often used in projects, with. Properties, and also in. xml format
Can be handled through the Java.utils.Property class.
1. Read the. properties file
[C-sharp]View PlainCopy
- File PFile = new File ("test.properties");
- FileInputStream pinstream=null;
- try {
- Pinstream = new FileInputStream (PFile);
- } catch (FileNotFoundException e) {
- E.printstacktrace ();
- }
- Properties P = new properties ();
- try {
- P.load (Pinstream);
- } catch (IOException e) {
- E.printstacktrace ();
- }
- Enumeration ENU = P.propertynames (); //Remove all keys
- P.list (System. Out);
- While (Enu.hasmoreelements ())
- {
- String ThisKey = (string) enu.nextelement ();
- System. out.println ("key=" +thiskey);
- System. out.println ("value=" +p.getproperty (ThisKey));
- }
The. Properties test file reads as follows:
Name = Tinyfun
Age = 25
Sex = Mans
title = Software Developer
2. Read the XML file
[Java]View PlainCopy
- File PFile = new File ("Test.xml");
- FileInputStream pinstream = null;
- try {
- Pinstream = new FileInputStream (PFile);
- Properties P = new properties ();
- P.loadfromxml (Pinstream);
- P.list (System.out);
- } catch (IOException e) {
- E.printstacktrace ();
- }
The XML file is as follows:
[XHTML]View PlainCopy
- <? XML version= "1.0" encoding="UTF-8" standalone="No"?>
- <! DOCTYPE Properties SYSTEM "Http://java.sun.com/dtd/properties.dtd">
- <properties>
- <comment>test</comment>
- <entry key="age">25</entry>
- <entry key="name">tinyfun</entry>
- <entry key="Sex">man</entry>
- <entry key="title">software developer</entry>
- </Properties>
3. Writing an XML file
[Java]View PlainCopy
- Properties P = new properties ();
- P.setproperty ("name","Tinyfun");
- P.setproperty ("age","25");
- P.setproperty ("Sex","man");
- P.setproperty ("title","software developer");
- try{
- PrintStream FW = new PrintStream (new File ("Test.xml"));
- P.storetoxml (FW,"test");
- } catch (IOException e) {
- E.printstacktrace ();
- }
4. Write to the. Properties file
[Java]View PlainCopy
- Properties P = new properties ();
- P.setproperty ("name","Tinyfun");
- P.setproperty ("age","25");
- P.setproperty ("Sex","man");
- P.setproperty ("title","software developer");
- try{
- PrintStream FW = new PrintStream (new File ("test.properties"));
- P.list (FW); }
- catch (IOException e) {
- E.printstacktrace ();
- }
Java Property class use