properties 类已不是新东西了,它在 java 编程的早期就有了,并且几乎没有什么变化。j2se 的 tiger 版本增强了这个类,不仅可以用它在单独一行中指定用等号分隔的多个键-值对,还可以用xml 文件装载和保存这些键-值对。 在 驯服 tiger的系列文章中,john zukowski 展示了如何驾驭这匹新一代的“役马”。
j2se 1.5 以前的版本要求直接使用 xml 解析器来装载配置文件并存储设置。虽然这并非是一件困难的事情,并且解析器是平台的标准部分,但是额外的工作总是有点让人烦。最近更新的 java.util.properties 类现在提供了一种为程序装载和存储设置的更容易的方法: loadfromxml(inputstream is) 和 storetoxml(outputstream os, string comment) 方法。
properties 基本知识
如果不熟悉 java.util.properties 类,那么现在告诉您它是用来在一个文件中存储键-值对的,其中键和值是用等号分隔的,如清单 1 所示。
清单 1. 一组属性示例
| foo=bar fu=baz |
| import java.util.*; import java.io.*; public class loadsample { public static void main(string args[]) throws exception { properties prop = new properties(); fileinputstream fis = new fileinputstream("sample.properties"); prop.load(fis); prop.list(system.out); system.out.println("\nthe foo property: " + prop.getproperty("foo")); } } |
| -- listing properties -- fu=baz foo=bar the foo property: bar |
| <?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> |
| <?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> |
| import java.util.*; import java.io.*; public class loadsamplexml { public static void main(string args[]) throws exception { properties prop = new properties(); fileinputstream fis = new fileinputstream("sampleprops.xml"); prop.loadfromxml(fis); prop.list(system.out); system.out.println("\nthe foo property: " + prop.getproperty("foo")); } } |
| 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 hen"); fileoutputstream fos = new fileoutputstream("rhyme.xml"); prop.storetoxml(fos, "rhyme"); fos.close(); } } |
| <?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 hen</entry> <entry key="three-four">shut the door</entry> <entry key="one-two">buckle my shoe</entry> </properties> |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器