JDK1.5 (codename Tiger) updated the Java.util.Properties class, provides a simple way to read the key-value to the property from the XML file: loadingFromxml () and StoreToxml ()
1. Method for basic loading attributes
l Sample property file: sample.properties
FOO = BAR
Fu = baz
l Add attribute Sample program
Import java.io.fileinputstream;
Import java.util.properties;
Public class loadsampleproperties {
Public static void main (string [] args) throws exception {
Properties Prop = New Properties ();
FileInputStream Fis = New FileInputStream ("Props / Sample.Properties);
Prop.Load (FIA);
Prop.List (System.out);
System.out.println ("/ NTHE Foo Property:" Prop.GetProperty ("foo"));
}
}
l The output is as follows:
- Listing Properties -
Fu = baz
FOO = BAR
The Foo Property: BAR
2, load attributes from XML
l The following is the Properties DTD list:
XML Version = "1.0" encoding = "UTF-8"?>
l Sample XML Property file: Sample.xml (in compliance with the toperties DTD)
XML Version = "1.0" encoding = "UTF-8"?>
Properties>
l
l
l Sample program loaded from XML file loading properties
Import java.io.fileinputstream; import java.util.properties;
Public class loadsamplexml {
Public static void main (string [] args) throws exception {
Properties Prop = New Properties ();
FileInputStream FII = New FileInputStream ("Props / Sample.xml");
Prop.LoadFromXML (FIS);
Prop.List (System.out);
System.out.println ("/ NTHE Foo Property:" Prop.GetProperty ("foo"));
}
}
l The result of the output is the same
l You can see that the method is simple: use the XML file to save the property, use the loadFromxml () method to replace the original LOAD () method to load the properties in the XML file.
3, update the attribute value in the XML file
l Sample program
Import java.io.fileinputstream;
Import java.io.fileoutputstream;
Import java.util.properties;
Public class updatesamplexml {
Public static void main (string [] args) throws exception {
Properties Prop = New Properties ();
FileInputStream FII = New FileInputStream ("Props / Sample.xml");
Prop.LoadFromXML (FIS);
Prop.List (System.out);
System.out.println ("/ NTHE Foo Property:" Prop.GetProperty ("foo"));
Prop.SetProperty ("foo", "Hello World!");
Prop.SetProperty ("New-Name", "New-Value");
FileOutputStream Fos = New FileoutputStream ("Props / Sample.xml");
Prop.StoreToxml (FOS, "STORE SAMPLE");
Fos.close ();
FIS = New FileInputStream ("PROPS / SAMPLE.XML");
Prop.LoadFromXML (FIS);
Prop.List (System.out);
System.out.println ("/ NTHE Foo Property:" Prop.GetProperty ("foo"));
}
}
l The above example loads the properties in sample.xml, updates the value of the foo attribute, and adds the new-name property, call the StoreToxml () method to save to the original file, and change the comment as a Store Sample
l The contents of Sample.xml after program execution are as follows:
XML Version = "1.0" encoding = "UTF-8"?>
Properties>