Link to home
Start Free TrialLog in
Avatar of ramnram
ramnram

asked on

appeding objects in file using ObjectOutputStream

i tried to append objects but i couldn't.
can anyone help me to solve this problem.

i've given sample code below.

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file1.txt",true));
................
...............
oos.writeObject(address);//address is an instance of a class Address

Avatar of sudhakar_koundinya
sudhakar_koundinya

Serializing

Object object = new javax.swing.JButton("push me");
   
    try {
        // Serialize to a file
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
        out.writeObject(object);
        out.close();
   
        // Serialize to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
        out = new ObjectOutputStream(bos) ;
        out.writeObject(object);
        out.close();
   
        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();
    } catch (IOException e) {
    }
Deserializing


    try {
        // Deserialize from a file
        File file = new File("filename.ser");
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        // Deserialize the object
        javax.swing.JButton button = (javax.swing.JButton) in.readObject();
        in.close();
   
        // Get some byte array data
        byte[] bytes = getBytesFromFile(file);
        // see e36 Reading a File into a Byte Array for the implementation of this method
   
        // Deserialize from a byte array
        in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        button = (javax.swing.JButton) in.readObject();
        in.close();
    } catch (ClassNotFoundException e) {
    } catch (IOException e) {
    }

class Address  implements Serializable
{
...
...
,..
}


  ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
        out.writeObject(new Address());




-----------------------------------------------------


        // Deserialize from a file
        File file = new File("filename.ser");
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        // Deserialize the object
        Address  address= (Address) in.readObject();
        in.close();
>> i tried to append objects but i couldn't.

Your class should implement Serializable interface
Try this, have tested it and make sure the class Address implements serializable.

Cheers!


package ee;
import java.io.*;

public class test {
      public test(){}
    public static void main(String args[])
    {
          try{
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/file1.txt",true));                
              Address address=new Address();
              oos.writeObject(address);//address is an instance of a class Address              
          }catch (IOException e){                      
                      System.out.println(e);
          }          
    }    
}


package ee;
import java.io.*;

public class Address implements Serializable{
      public String test;
      public Address(){
            test="Test";            
      }
}


Avatar of ramnram

ASKER

Thanx for ur response.

But how can i retrieve the objects that we wrote in to the file.

i got an exception "StreamCurruptedException" after reading the first record.

I have given the code below.

Run the code atleast twice. so that the file contains more than one record.

import java.io.*;

public class test {
     public test(){}
    public static void main(String args[])
    {
         try{
               
              ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/file1.txt",true));              
             Address address=new Address();
             oos.writeObject(address);//address is an instance of a class Address            
         }catch (IOException e){                  
                   System.out.println(e);
         }        
        try{
              ObjectInputStream oos = new ObjectInputStream(new FileInputStream("c:/file1.txt"));              
              while(true)
              {
                          Address address=new Address();
                          address=(Address)oos.readObject();//address is an instance of a class Address                   
                          System.out.println("\n " + address.test);
              }
             
            }catch (Exception e){ System.out.println(e);       }        
 
    }    
}
class Address implements Serializable{
     public String test;
     public Address(){
          test="popopppopp";          
     }
}
If you save an object of Class A and after and object of class B, when you read you must take first the object of Class A and then the object of Class B. And both must be serializable.
In your case you must close the file before you read.
put
oos.flush();
oos.close();
before opening again the file.
Guess your file file1.txt has contains when you run your script?

I tried your program and did not get the same problem as you mentioned.

Maybe just delete the file file1.txt and rerun your program to make sure your file is empty.

Should be ok. :)
Avatar of ramnram

ASKER


My actual need is to store and read list of addresses to or from a file.
i've written program to do so that i've given below.

the problem is i unable to append and read back all records.it doesn't give
any compile or runtime errors.


public class Address implements Serializable
{
      String name;
      String phone;
      String email;
      public void set(String nAme,String Phone,String Email)
      {
            name=nAme;
            phone=Phone;
            email=Email;            
      }
      public void display()
      {
            System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
      }
      private static String putChar(String chr,int no)//It returns a string of given char no of times
      {      String s="";
            for (int i=0;i<no ;i++ ){s=s+ chr;}
            return s;
      }
}
 class AddressBook extends ArrayList
 {
       public void addAddress(ObjectOutputStream oos,String name,String phone,String email) throws Exception
      {
            Address address=new Address();
            address.set(name,phone,email);
            oos.writeObject(address);
      }
        public void loadAddress(ObjectInputStream ois) throws Exception
      {            
            Address address;
            boolean again=true;
            while(again)
            {      try
                  {
                        address=(Address)ois.readObject();
                        this.add(address);
                  }
                  catch(Exception e)
                  {      again=false;}
            }
            ois.close();
      }
      public void displayAddress()
      {      
            for(int i=0;i<this.size();i++)
            {
                  Address address =(Address)this.get(i);
                  address.display();
            }
            System.out.println("No of Records:" + this.size());      
      }
}
class AddBook
{
      public static void main (String [] arguments)throws Exception
      {                        
            int option;
            boolean again=true;
            String temp;
            BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
            while(again)
                  {
                        System.out.println("\n\n   ADDRESS BOOK");//Menu items to be displayed
                        System.out.println("   ------------");
                        System.out.println("\n   1. ADD");
                        System.out.println("   2. LIST");
                        
                        System.out.println("   5. EXIT");
                        System.out.print("\n\n Enter your option: ");

                        temp=input.readLine();
                        option=(isNumeric(temp)?Integer.parseInt(temp):0);
                        
                                  
                              switch(option)
                              {
                                    case 1: //To Add new contacts to Addres Book
                                          readAddress();
                                          break;
                                    case 2: //To Display contacts in the Addres Book
                                          displayAddress();
                                          break;
                                                                  case 5://To exit from the Addres Book
                                          again=false;
                                          break;
                                    default://Other than option given
                                          System.out.println("\n Invalid option.");
                              }
                              System.out.print("\n\n\n\n Press enter to continue...");      
                              temp=input.readLine();
                        }
                        
      }
      static void displayAddress()throws Exception
      {      
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBook.txt"));
            AddressBook aBook = new AddressBook ();
            aBook.loadAddress(ois);
            aBook.displayAddress();
            ois.close();
      }
      static void readAddress()throws Exception
      {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBook.txt",true));
            BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
            AddressBook aBook = new AddressBook ();
            String name,phone,email;
                        
            System.out.print("\nEnter name:");
            name=br.readLine();
            
            System.out.print("\nEnter phone:");
            phone=br.readLine();
            
            System.out.print("\nEnter email:");
            email=br.readLine();
            
            aBook.addAddress(oos,name,phone,email);
            oos.close();
      }
      static boolean isNumeric(String str)throws Exception
      {
            try
            {      int t=Integer.parseInt(str);
                  return true;
            }
            catch(NumberFormatException e)       {return false;}
      }
}





put oos.flush();
         aBook.addAddress(oos,name,phone,email);
          oos.flush();<---------------------insert here.
          oos.close();
Avatar of ramnram

ASKER

fredwangus,

I tried ur suggestion. but it made no difference.

This is wat i hav at the end of second execution of program.


------------->File1.txt<----------------------
¬í sr Address¡wóðB­Ìê L testt Ljava/lang/String;xpt
popopppopp
¬í sr Address¡wóðB­Ìê L testt Ljava/lang/String;xpt       dffdfdfff

-------------------->end of File1.txt<--------------------

U can see every record contains a header..(¬í sr Address¡wóðB­Ìê L testt Ljava/lang/String;xpt  --> is a header)

i am using java1.4.2 version.
I created 3 files using your code and run AddBook, acturally your program is functioning properly.

Attached the code I used and see whether it works at your side or not:

package ee;
import java.io.*;

class AddBook
{
     public static void main (String [] arguments)throws Exception
     {                    
          int option;
          boolean again=true;
          String temp;
          BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
          while(again)
               {
                    System.out.println("\n\n   ADDRESS BOOK");//Menu items to be displayed
                    System.out.println("   ------------");
                    System.out.println("\n   1. ADD");
                    System.out.println("   2. LIST");                    
                    System.out.println("   5. EXIT");
                    System.out.print("\n\n Enter your option: ");

                    temp=input.readLine();
                    option=(isNumeric(temp)?Integer.parseInt(temp):0);
                   
                             
                         switch(option)
                         {
                              case 1: //To Add new contacts to Addres Book
                                   readAddress();
                                   break;
                              case 2: //To Display contacts in the Addres Book
                                   displayAddress();
                                   break;
                                                       case 5://To exit from the Addres Book
                                   again=false;
                                   break;
                              default://Other than option given
                                   System.out.println("\n Invalid option.");
                         }
                         System.out.print("\n\n\n\n Press enter to continue...");    
                         temp=input.readLine();
                    }
                   
     }
     static void displayAddress()throws Exception
     {    
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBook.txt"));
          AddressBook aBook = new AddressBook ();
          aBook.loadAddress(ois);
          aBook.displayAddress();
          ois.close();
     }
     static void readAddress()throws Exception
     {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBook.txt",true));
          BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
          AddressBook aBook = new AddressBook ();
          String name,phone,email;
                   
          System.out.print("\nEnter name:");
          name=br.readLine();
         
          System.out.print("\nEnter phone:");
          phone=br.readLine();
         
          System.out.print("\nEnter email:");
          email=br.readLine();
         
          aBook.addAddress(oos,name,phone,email);
          oos.close();
     }
     static boolean isNumeric(String str)throws Exception
     {
          try
          {     int t=Integer.parseInt(str);
               return true;
          }
          catch(NumberFormatException e)      {return false;}
     }
}

/*
 * Created on Oct 4, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package ee;
import java.io.*;

public class Address implements Serializable
{
     String name;
     String phone;
     String email;
     public void set(String nAme,String Phone,String Email)
     {
          name=nAme;
          phone=Phone;
          email=Email;          
     }
     public void display()
     {
          System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
     }
     private static String putChar(String chr,int no)//It returns a string of given char no of times
     {    
           String s="";
          for (int i=0;i<no ;i++ ){s=s+ chr;}
          return s;
     }
}

package ee;
import java.io.*;
import java.util.*;

class AddressBook extends ArrayList
{
     public void addAddress(ObjectOutputStream oos,String name,String phone,String email) throws Exception
    {
         Address address=new Address();
         address.set(name,phone,email);
         oos.writeObject(address);        
    }
      public void loadAddress(ObjectInputStream ois) throws Exception
    {          
         Address address;
         boolean again=true;
         while(again)
         {     try
              {
                   address=(Address)ois.readObject();
                   this.add(address);
              }
              catch(Exception e)
              {     again=false;}
         }
         ois.close();
    }
    public void displayAddress()
    {    
         for(int i=0;i<this.size();i++)
         {
              Address address =(Address)this.get(i);
              address.display();
         }
         System.out.println("No of Records:" + this.size());    
    }
}
Avatar of ramnram

ASKER

hi giant2,
  Thanks 4 ur suggestion. but still(after putting flush(); in that place) i'm getting the same problem.
try this

import java.util.*;
import java.io.*;

public class test {
  public test() {}

  public static void main(String args[]) {
    test tes = new test();
    Object[] array = tes.deserialize();
    tes.serialize(array, new Address());

  }

  public void serialize(Object[] array, Object object) {
    try {
      // Serialize to a file
      ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
          "filename.ser", true));
      for (int i = 0; i < array.length; i++) {
        out.writeObject(array[i]);
      }
      out.writeObject(object);
      out.flush();
      out.close();
    }
    catch (Exception ex) {

    }

  }

  public Object[] deserialize() {
    File file = new File("filename.ser");
    Vector vect = new Vector();
    ObjectInputStream in = null;
    try {
      // Deserialize from a file
      in = new ObjectInputStream(new FileInputStream(file));

      // Deserialize the object
      while (true) {
        Address add = (Address) in.readObject();

        if (add == null) {
          break;

        }
        vect.add(add);
        System.err.println(add.test);
      }
      in.close();

    }
    catch (Exception ex) {
      System.err.println(ex);
    }
    return vect.toArray();
  }

}

class Address
    implements Serializable {
  public String test;
  public Address() {
    test = "popopppopp";
  }
}
Or try this

 XMLEncoder e = new XMLEncoder(
                          new BufferedOutputStream(
                              new FileOutputStream("addresses.xml",true)));
       e.writeObject(new Address());
       e.close();

XMLDecoder d = new XMLDecoder(
                          new BufferedInputStream(
                              new FileInputStream("doctors.xml")));
       Address add = (Address)d.readObject();
       d.close();

Avatar of ramnram

ASKER

fredwangus ,
  did u try with option 2 (while excuting the program)to list out records and did u get all records from the file?
import java.util.*;
import java.io.*;
import java.beans.*;

public class test {
  public test() {}

  public static void main(String args[]) {
    test tes = new test();

    tes.serialize(new Address());

  }

  public void serialize(Object object) {
    try {
      XMLEncoder e = new XMLEncoder(
          new BufferedOutputStream(
          new FileOutputStream("addresses.xml", true)));
      e.writeObject(new Address());
      e.close();

    }
    catch (Exception ex) {

    }

  }

  public void deserialize() {

    try {
      XMLDecoder d = new XMLDecoder(
          new BufferedInputStream(
          new FileInputStream("addresses.xml")));
      while (true) {
        Address add = (Address) d.readObject();
        if (add == null) {
          break;
        }
      }
      d.close();

    }
    catch (Exception ex) {
      System.err.println(ex);
    }

  }

}

class Address
    implements Serializable {
  public String test;
  public Address() {
    test = "popopppopp";
  }
}
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you write the setters and getters to your class,
then this model is good for your requirement

public class Address
     {
  private String test;
  public Address() {

  }
  public void setTest(String str)
      {
        test=str;
      }
      public String getTest()
      {
            return test;
      }
}



import java.util.*;
import java.io.*;
import java.beans.*;

public class test {
  public test() {}

  public static void main(String args[]) {
    test tes = new test();

     Address array[]=tes.readObjects();
     
     for(int i=0;i<array.length;i+=1)
     {
       tes.add(array[i]);
     }
     Address add=new Address();
     add.setTest(args[0]);
     tes.add(add);
     

  }
 
  public Address[] readObjects()
  {
   Vector vect=new Vector();
    try {
      XMLDecoder d = new XMLDecoder(
          new BufferedInputStream(
          new FileInputStream("addresses.xml")));
      while (true) {
        Address add = (Address) d.readObject();
        if (add == null) {
          break;
        }
        vect.add(add);
      }
      d.close();

    }
    catch (Exception ex) {
      System.err.println(ex);
    }
    return (Address[])vect.toArray(new Address[0]);
  }

  public void add(Object object) {
    try {
      XMLEncoder e = new XMLEncoder(
          new BufferedOutputStream(
          new FileOutputStream("addresses.xml", true)));
      e.writeObject(new Address());
      e.close();

    }
    catch (Exception ex) {

    }

  }



}

You'd be much better off serializing a List of Address

List addresses = new ArrayList();
addresses.add(new Address(name, phone, email));
ooOut.writeObject(addresses);

........

List addresses = (List)ooIn.readObject(addressList);
// append one
addresses.add(new Address(name2, phone2, email2));
ooOut.writeObject(addresses);

> You'd be much better off serializing a List of Address

Already mentioned.
and it's not a case of being better off, thats how it needs to be done.
This must be your final model, if u depend on XMLEncoder and XMLDecoder

import java.util.*;
import java.io.*;
import java.beans.*;

public class test {
  public test() {}

  public static void main(String args[]) {
    test tes = new test();

    Address array[] = tes.loadObjects();

    Address add = new Address();
    add.setTest(args[0]);
    tes.add(array,add);
      tes.readObjects();

  }

  public Address[] loadObjects() {
    Vector vect = new Vector();
    try {
      XMLDecoder d = new XMLDecoder(
          new BufferedInputStream(
          new FileInputStream("addresses.xml")));
      while (true) {
        Address add = (Address) d.readObject();
        if (add == null) {
          break;
        }
        vect.add(add);
            System.err.println(add.getTest());
      }
      d.close();

    }
    catch (Exception ex) {
      System.err.println(ex);
    }
    return (Address[]) vect.toArray(new Address[0]);
  }


    public void  readObjects() {

    try {
      XMLDecoder d = new XMLDecoder(
          new BufferedInputStream(
          new FileInputStream("addresses.xml")));
      while (true) {
        Address add = (Address) d.readObject();
        if (add == null) {
          break;
        }
 
            System.err.println(add.getTest());
      }
      d.close();

    }
    catch (Exception ex) {
     
    }
 
  }

  public void add(Address[] array, Object object) {
    try {
      XMLEncoder e = new XMLEncoder(
          new BufferedOutputStream(
          new FileOutputStream("addresses.xml")));
      for (int i = 0; i < array.length; i++) {
        e.writeObject(array[i]);
      }
      e.writeObject(object);
      e.close();

    }
    catch (Exception ex) {

    }

  }

}

_________________________________________________________________________________________

public class Address implements Serializable
     {
  private String test;
  public Address() {

  }
  public void setTest(String str)
      {
        test=str;
      }
      public String getTest()
      {
            return test;
      }
}
Avatar of ramnram

ASKER

Sudhakar,
 Thanks for ur lot of suggestions, but we needed simple core java program.
so your code would end up looking something like:


     static void readAddress()throws Exception
     {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBook.txt"));
          BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
          AddressBook aBook = new AddressBook ();
          String name,phone,email;
                   
          System.out.print("\nEnter name:");
          name=br.readLine();
         
          System.out.print("\nEnter phone:");
          phone=br.readLine();
         
          System.out.print("\nEnter email:");
          email=br.readLine();
         
          aBook.addAddress(name,phone,email);
          oos.writeObject(aBook);
          oos.close();
     }

     ...


 class AddressBook extends ArrayList
 {
      public void addAddress(String name,String phone,String email) throws Exception
     {
          Address address=new Address();
          address.set(name,phone,email);
          add(address);
     }
 ...
Actually more like this:


class AddBook
{
     private static AddressBook aBook;

     public static void main (String [] arguments)throws Exception
     {                    
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBook.txt"));
          aBook = (AddressBook) ois.readObject();
          ois.close();

          int option;
          boolean again=true;
          String temp;
          BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
          while(again)
               {
                    System.out.println("\n\n   ADDRESS BOOK");//Menu items to be displayed
                    System.out.println("   ------------");
                    System.out.println("\n   1. ADD");
                    System.out.println("   2. LIST");
                   
                    System.out.println("   5. EXIT");
                    System.out.print("\n\n Enter your option: ");

                    temp=input.readLine();
                    option=(isNumeric(temp)?Integer.parseInt(temp):0);
                   
                             
                         switch(option)
                         {
                              case 1: //To Add new contacts to Addres Book
                                   readAddress();
                                   break;
                              case 2: //To Display contacts in the Addres Book
                                   displayAddress();
                                   break;
                                                       case 5://To exit from the Addres Book
                                   again=false;
                                   break;
                              default://Other than option given
                                   System.out.println("\n Invalid option.");
                         }
                         System.out.print("\n\n\n\n Press enter to continue...");    
                         temp=input.readLine();
                    }
                   
     }
     static void displayAddress()throws Exception
     {    
          aBook.displayAddress();
     }
     static void readAddress()throws Exception
     {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBook.txt",true));
          BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
          String name,phone,email;
                   
          System.out.print("\nEnter name:");
          name=br.readLine();
         
          System.out.print("\nEnter phone:");
          phone=br.readLine();
         
          System.out.print("\nEnter email:");
          email=br.readLine();
         
          aBook.addAddress(name,phone,email);
          oos.writeObject(aBook);
          oos.close();
     }
     static boolean isNumeric(String str)throws Exception
     {
          try
          {     int t=Integer.parseInt(str);
               return true;
          }
          catch(NumberFormatException e)      {return false;}
     }
}

 class AddressBook extends ArrayList
 {
      public void addAddress(String name,String phone,String email) throws Exception
     {
          Address address=new Address();
          address.set(name,phone,email);
          add(address);
     }

     public void displayAddress()
     {    
          for(int i=0;i<this.size();i++)
          {
               Address address =(Address)this.get(i);
               address.display();
          }
          System.out.println("No of Records:" + this.size());    
     }
}
>>Thanks for ur lot of suggestions, but we needed simple core java program.


Serialization using XMLEncoder and XMLDecoder model is very easy and simple to understand
try this one, in option 2, i can list down all records.

Please note to delete the address.txt before you run the application.

package ee;
import java.io.*;
import java.util.*;

class AddressBook extends ArrayList
{
     public void addAddress(ObjectOutputStream oos,String name,String phone,String email) throws Exception
    {
         Address address=new Address();
         address.set(name,phone,email);
         oos.writeObject(address);        
    }
    public void loadAddress(ObjectInputStream ois) throws Exception
    {          
         Address address;
         boolean again=true;
         while(again)
         {    
               try
              {
                   address=(Address)ois.readObject();
                   this.add(address);
              }
              catch(java.io.EOFException e){
                    again=false;
              }
                    //again=false;}
         }
         ois.close();
    }
    public void displayAddress()
    {    
         for(int i=0;i<this.size();i++)
         {
              Address address =(Address)this.get(i);
              address.display();
         }
         System.out.println("No of Records:" + this.size());    
    }
}

package ee;
import java.io.*;

public class Address implements Serializable
{
     String name;
     String phone;
     String email;
     public void set(String nAme,String Phone,String Email)
     {
          name=nAme;
          phone=Phone;
          email=Email;          
     }
     public void display()
     {
          System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
     }
     private static String putChar(String chr,int no)//It returns a string of given char no of times
     {    
           String s="";
          for (int i=0;i<no ;i++ ){s=s+ chr;}
          return s;
     }
}

package ee;
import java.io.*;

class AddBook
{
       public static void main (String [] arguments)throws Exception
     {      
             ObjectOutputStream oos=null;
             try{oos = new ObjectOutputStream(new FileOutputStream("C:/AddBook.txt",true));}
             catch (Exception e){System.out.println(e);}
                          int option;
          boolean again=true;
          String temp;
          BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
          while(again)
               {
                    System.out.println("\n\n   ADDRESS BOOK");//Menu items to be displayed
                    System.out.println("   ------------");
                    System.out.println("\n   1. ADD");
                    System.out.println("   2. LIST");                    
                    System.out.println("   5. EXIT");
                    System.out.print("\n\n Enter your option: ");

                    temp=input.readLine();
                    option=(isNumeric(temp)?Integer.parseInt(temp):0);
                   
                             
                         switch(option)
                         {
                              case 1: //To Add new contacts to Addres Book
                                   readAddress(oos);
                                   break;
                              case 2: //To Display contacts in the Addres Book
                                   displayAddress();
                                   break;
                              case 5://To exit from the Addres Book
                                   again=false;
                                   break;
                              default://Other than option given
                                   System.out.println("\n Invalid option.");
                         }
                         System.out.print("\n\n\n\n Press enter to continue...");    
                         temp=input.readLine();
                    }                    
     }
     static void displayAddress()throws Exception
     {    
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBook.txt"));
          AddressBook aBook = new AddressBook ();
          aBook.loadAddress(ois);
          aBook.displayAddress();
          ois.close();
     }
     static void readAddress(ObjectOutputStream oos)throws Exception
     {          
          BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
          AddressBook aBook = new AddressBook ();
          String name,phone,email;
                   
          System.out.print("\nEnter name:");
          name=br.readLine();
         
          System.out.print("\nEnter phone:");
          phone=br.readLine();
         
          System.out.print("\nEnter email:");
          email=br.readLine();
         
          aBook.addAddress(oos,name,phone,email);          
     }
     static boolean isNumeric(String str)throws Exception
     {
          try
          {     int t=Integer.parseInt(str);
               return true;
          }
          catch(NumberFormatException e)      {return false;}
     }
}

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ramnram

ASKER

fredwangus,
  But, I wanted records to be permenant in the file.
did u try the changes I posted, they should meet your needs.

try my code.
Copy and paste.
Bye, Giant.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ramnram,
copy, paste, compile, execute the code I post.
It goes good and solve your problem.

Bye, Giant.
Avatar of ramnram

ASKER

let me analyze all ur codes.

just giv me some time.
Avatar of ramnram

ASKER

U guys deserved it.
:)