`

Properties的store()方法和load()方法 示例

    博客分类:
  • Java
UP 
阅读更多

/*

Properties的一个最有用的方面是可以利用store()方法和load()方法方便地对包含在属性(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 strName,strNumber;
  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 exsiting
   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): ");
   strName = br.readLine();
   if(strName.equals("quit")) continue;

   System.out.println("Enter number:");
   strNumber = br.readLine();

   ht.put(strName,strNumber);
   changed = true;
  }while(!strName.equals("quit"));

  //If phonebook 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 stop): ");
   strName = br.readLine();
   if(strName.equals("quit")) continue;
   strNumber = (String)ht.get(strName);
   System.out.println(strNumber);
  }while(!strName.equals("quit"));
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics