Java. util. properties class

Source: Internet
Author: User

The properties class is no longer a new thing. It was created in the early stage of Java programming and has almost no changes. The tiger version of j2se enhances this class, not only can it be used to specify multiple key-value pairs separated by equal signs in a single row, you can also load and save these key-value pairs using XML files. In this article to tame tiger, John zukoski demonstrated how to control this new generation of "service Horse ". Share your thoughts on this article with the author and other readers in the Forum corresponding to this article (you can also click the discussion at the top or bottom of the article to visit this forum ).

Versions earlier than j2se 1.5 require that the XML Parser be used directly to load the configuration file and store the settings. Although this is not a difficult task, and the parser is the standard part of the platform, the extra work is always a bit annoying. Recently updated Java. util. the properties class now provides an easier way to configure program loading and storage: loadfromxml (inputstream is) and storetoxml (outputstream OS, string comment.

Basic Properties knowledge
If you are not familiar with Java. util. properties class, which is used to store key-value pairs in a file. The key-value pairs are separated by equal signs, as shown in Listing 1.

Listing 1. Example of a group of Properties

Foo = bar
Fu = Baz

After listing 1 is loaded into the properties object, you can find two keys (FOO and Fu) and two values (Bar of Foo and Baz of Fu. This class supports embedding Unicode strings with/u, but here it is important that each item is treated as a string.

Listing 2 shows how to load an attribute file and list its current set of keys and values. You only need to pass the inputstream of this file to the load () method, and then add each key-value pair to the properties instance. Use List () to list all attributes or use getproperty () to obtain individual attributes.

Listing 2. Loading attributes

Import java. util .*;
Import java. Io .*;

Public class loadsample {
Public static void main (string ARGs []) throws exception {
Properties prop = new properties ();
Fileinputstream FCM =
New fileinputstream ("sample. properties ");
Prop. Load (FS );
Prop. List (system. Out );
System. Out. println ("/nthe Foo property:" +
Prop. getproperty ("foo "));
}
}

Run the loadsample program to generate the output shown in listing 3. Note that the order of the output key-value pairs in the list () method is different from that in the input file. The properties class stores a group of key-value pairs in a hash (hashtable, actually a hashtable subclass), so the sequence cannot be guaranteed.

Listing 3. loadsample output

-- Listing properties --
Fu = Baz
Foo = bar

The Foo property: bar

XML property File
There is nothing new here. The properties class always works like this. However, the new feature is to load a set of attributes from an XML file. Its DTD is shown in Listing 4.

Listing 4. Attribute DTD

<? XML version = "1.0" encoding = "UTF-8"?>
<! -- DTD for properties -->
<! Element properties (comment ?, Entry *)>
<! ATTLIST properties version CDATA # fixed" 1.0 ">
<! Element comment (# pcdata)>
<! Element entry (# pcdata)>
<! ATTLIST Entry key CDATA # required>

If you do not want to read the xml dtd carefully, you can tell that it is actually a <comment> label encapsulated in the <Properties> tag, followed by any number of <entry> labels. Each <entry> tag has a key attribute, and the input content is its value. Listing 5 shows what the XML version of the property file in Listing 1 looks like.

Listing 5. XML Attribute File

<? 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>

As shown in Listing 6, the properties file for reading the XML version is no different from the file for reading the old format.

Listing 6. Read the XML properties File

Import java. util .*;
Import java. Io .*;

Public class loadsamplexml {
Public static void main (string ARGs []) throws exception {
Properties prop = new properties ();
Fileinputstream FCM =
New fileinputstream ("sampleprops. xml ");
Prop. loadfromxml (FCM );
Prop. List (system. Out );
System. Out. println ("/nthe Foo property:" +
Prop. getproperty ("foo "));
}
}

Description of resource binding
Although the java. util. properties class currently supports both key-value pairs and attribute files as XML files, unfortunately, there is no built-in option to process resourcebundle as an XML file. Yes, propertyresourcebundle does not use the properties object to load bindings, but the loading method is hard-coded into the class, rather than the newer loadfromxml () method.

Run the program in Listing 6 to generate the same output as the original program, as shown in Listing 2.

Save XML attributes
Another feature of the new properties is to store properties in XML files. Although the store () method still creates a file similar to the one shown in Listing 1, you can use the new storetoxml () method to create the file shown in listing 5. You only need to pass an outputstream and a string for annotation. Listing 7 shows the new storetoxml () method.

Listing 7. Store properties as an XML file

Import java. util .*;
Import java. Io .*;

Public class storexml {
Public static void main (string ARGs []) throws exception {
Properties prop = new properties ();
Prop. setproperty ("One-Two", "buckle my shoe ");
Prop. setproperty ("three-four", "Shut the door ");
Prop. setproperty ("five-six", "pick up sticks ");
Prop. setproperty ("seven-eight", "lay them straight ");
Prop. setproperty ("nine-ten", "a big, fat success ");
Fileoutputstream Fos =
New fileoutputstream ("rhyme. xml ");
Prop. storetoxml (FOS, "rhyme ");
FOS. Close ();
}
}

The output produced by running the program in listing 7 is shown in listing 8.

Listing 8. Stored XML files

<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype properties system "http://java.sun.com/dtd/properties.dtd">
<Properties>
<Comment> rhyme </comment>
<Entry key = "seven-eight"> lay them straight </entry>
<Entry key = "five-six"> pick up sticks </entry>
<Entry key = "nine-ten"> a big, fat week </entry>
<Entry key = "three-four"> shut the door </entry>
<Entry key = "One-Two"> buckle my shoe </entry>
</Properties>

Conclusion
Whether to use XML files or old-fashioned a = B files depends entirely on you. Old files must be lightweight from the memory perspective. However, due to the widespread use of XML, it is expected that the XML format will become popular because it has been widely used, but does not use the properties object. Select all at you. Analyze the source code of the private xmlutils class to obtain more information about the XML parsing.

 

 

 

Ptest. Java
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. util. properties;
/**
* Read the properties File
* @ Author bbflyerwww
* @ Date 2006-08-02
*/
Public class Ptest {
Public static void main (string [] ARGs ){
Try {
Long start = system. currenttimemillis ();
Inputstream is = new fileinputstream ("Conf. properties ");
Properties P = new properties ();
P. Load (is );
Is. Close ();
System. Out. println ("Size:" + P. Size ());
System. Out. println ("homepage:" + P. getproperty ("Homepage "));
System. Out. println ("Author:" + P. getproperty ("author "));
System. Out. println ("School:" + P. getproperty ("school "));
System. Out. println ("Date:" + P. getproperty ("date "));
Long end = system. currenttimemillis ();
System. Out. println ("cost:" + (end-Start ));
} Catch (ioexception IOE ){
IOE. printstacktrace ();
}
}
}

Conf. Properties
# Configuration file
Homepage = http://hi.baidu.com/bbflyerwww
Author = bbflyerwww
School = Wuhan University
Date = 2006-08-02

Result
Size: 4
Homepage: http://hi.baidu.com/bbflyerwww
Author: bbflyerwww
School: Wuhan University
Date: 2006-08-02
Cost: 0

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.