15.10.7 使用store( )和load( ) Properties的一个最有用的方面是可以利用store( )和load( )方法方便地对包含在属性(Properties)对象中的信息进行存储或从盘中装入信息。在任何时候,都可以将一个属性(Properties)对象写入流或从中将其读出。这使得属性列表特别方便实现简单的数据库。例如,下面的程序使用属性列表创建一个简单的用计算机处理的存储着姓名和电话号码的电话本。为了寻找某人的电话号码,可输入他或者她的名字。程序使用store( )和load( )方法来存储和检索列表。当程序执行时,它首先试着从一个叫做phonebook.dat的文件中装入列表。如果这个文件存在,列表就被装入。然后就可以增加列表。如果这样做了,当终止程序时,新列表就会被保存。注意:实现一个小且实用的计算机化的电话号码本只需要很少的程序代码。 /* A simple telephone number database that uses a property list. */ import java.io.*; import java.util.*; class Phonebook { public static void main(String args[]) throws IOException { Properties ht = new Properties(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String name, number; FileInputStream fin = null; boolean changed = false; // Try to open phonebook.dat file. try { fin = new FileInputStream(“phonebook.dat”); } catch(FileNotFoundException e) { // ignore missing file } /* If phonebook file already exists, load existing telephone numbers. */ try { if(fin != null) { ht.load(fin); fin.close(); } } catch(IOException e) { System.out.println(“Error reading file.”); } // Let user enter new names and numbers. do { System.out.println(“Enter new name” + ” (‘quit’ to stop): “); name = br.readLine(); if(name.equals(“quit”)) continue; System.out.println(“Enter number: “); number = br.readLine(); ht.put(name, number); changed = true; } while(!name.equals(“quit”)); // If phone book data has changed, save it. if(changed) { FileOutputStream fout = new FileOutputStream(“phonebook.dat”); ht.store(fout, “Telephone Book”); fout.close(); } // Look up numbers given a name. do { System.out.println(“Enter name to find” + ” (‘quit’ to quit): “); name = br.readLine(); if(name.equals(“quit”)) continue; number = (String) ht.get(name); System.out.println(number); } while(!name.equals(“quit”)); } } 15.11 类集总结 类集框架为程序员提供了一个功能强大的设计方案以解决编程过程中面临的大多数任务。下一次当你需要存储和检索信息时,可考虑使用类集。记住,类集不仅仅是专为那些“大型作业”,例如联合数据库,邮件列表或产品清单系统等所专用的。它们对于一些小型作业也是很有效的。例如,TreeMap可以给出一个很好的类集以保留一组文件的字典结构。TreeSet在存储工程管理信息时是十分有用的。坦白地说,对于采用基于类集的解决方案而受益的问题种类只受限于你的想象力。 远离城市的喧嚣,寻找一份宁静,