• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

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

0
ramnram
Asked:
ramnram
  • 12
  • 9
  • 8
  • +3
4 Solutions
 
sudhakar_koundinyaCommented:
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) {
    }
0
 
sudhakar_koundinyaCommented:
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) {
    }

0
 
sudhakar_koundinyaCommented:
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();
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
sudhakar_koundinyaCommented:
>> i tried to append objects but i couldn't.

Your class should implement Serializable interface
0
 
fredwangusCommented:
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";            
      }
}


0
 
ramnramAuthor Commented:
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";          
     }
}
0
 
Giant2Commented:
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.
0
 
Giant2Commented:
In your case you must close the file before you read.
0
 
Giant2Commented:
put
oos.flush();
oos.close();
before opening again the file.
0
 
fredwangusCommented:
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. :)
0
 
ramnramAuthor Commented:

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;}
      }
}





0
 
Giant2Commented:
put oos.flush();
         aBook.addAddress(oos,name,phone,email);
          oos.flush();<---------------------insert here.
          oos.close();
0
 
ramnramAuthor Commented:
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.
0
 
fredwangusCommented:
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());    
    }
}
0
 
ramnramAuthor Commented:
hi giant2,
  Thanks 4 ur suggestion. but still(after putting flush(); in that place) i'm getting the same problem.
0
 
sudhakar_koundinyaCommented:
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";
  }
}
0
 
sudhakar_koundinyaCommented:
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();

0
 
ramnramAuthor Commented:
fredwangus ,
  did u try with option 2 (while excuting the program)to list out records and did u get all records from the file?
0
 
sudhakar_koundinyaCommented:
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";
  }
}
0
 
objectsCommented:
you can't append to the file using object serialization, you'll need to create a new file each time you save and save the entire list.

oos.write(aBook);
0
 
sudhakar_koundinyaCommented:
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) {

    }

  }



}

0
 
CEHJCommented:
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);

0
 
objectsCommented:
> 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.
0
 
sudhakar_koundinyaCommented:
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;
      }
}
0
 
ramnramAuthor Commented:
Sudhakar,
 Thanks for ur lot of suggestions, but we needed simple core java program.
0
 
objectsCommented:
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);
     }
 ...
0
 
objectsCommented:
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());    
     }
}
0
 
sudhakar_koundinyaCommented:
>>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
0
 
fredwangusCommented:
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;}
     }
}

0
 
Giant2Commented:
try this:
this do all that you want (append a new record and use only 1 file).
import java.util.*;
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;
      }
}
class AddressBook extends ArrayList {
      public void addAddress(String fileName, String name, String phone, String email) throws Exception {
            try{
            loadAddress(new ObjectInputStream(new FileInputStream(fileName)));
            }catch (Exception ex){}
            File fil=new File(fileName);
            fil.delete();
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName, true));
            try{
            System.out.println("read:"+this.size());
            for (int i = 0; i < this.size(); i++) {
                  oos.writeObject((Address)this.get(i));
            }
            Address address = new Address();
            address.set(name, phone, email);
            oos.writeObject(address);
            oos.flush();
            }catch (Exception ex){}
            oos.close();
      }
      public void loadAddress(ObjectInputStream ois) throws Exception {
            this.removeAll(this);
            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 {
            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("C:/AddBook.txt", name, phone, email);
      }
      static boolean isNumeric(String str) throws Exception {
            try {
                  int t = Integer.parseInt(str);
                  return true;
            } catch (NumberFormatException e) {
                  return false;
            }
      }
}

Bye, Giant.
0
 
ramnramAuthor Commented:
fredwangus,
  But, I wanted records to be permenant in the file.
0
 
objectsCommented:
did u try the changes I posted, they should meet your needs.

0
 
Giant2Commented:
try my code.
Copy and paste.
Bye, Giant.
0
 
fredwangusCommented:
It seems write object might not be a good idea.

Maybe only write the name, email and phone as strings to a file each time instead of objects.

0
 
sudhakar_koundinyaCommented:
For the class below, I am giving two fully working models - one is with XML saving and reading and one is directly dumping the objects and reading. You can test both and choose the best you need. Both works perfectly.


Regards
Sudhakar


import java.io.*;

public class AddressBook
    implements Serializable {
  public AddressBook() {
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  public String getPhone() {
    return phone;
  }

  public void setMail(String mail) {
    this.mail = mail;
  }

  public String getMail() {
    return mail;
  }

  private String name = null;
  private String phone = null;
  private String mail = null;
}



____________________________________________________________________________________________

                                                     Object Serialization (NON XML Implementation)
________________________________________________________________________________________________

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

public class AddressBookTest {
  public AddressBookTest() {
  }

  public static void main(String s[]) throws Exception {
    AddressBookTest test = new AddressBookTest();
    Object[] array = null;
    try {
      array = test.loadObjects(new FileInputStream("c:/addresses.ser"));
    }
    catch (Exception ex) {
    }
    AddressBook book = new AddressBook();
    book.setName(s[0]);
    book.setPhone(s[1]);
    book.setMail(s[2]);
    test.add(book, array, new FileOutputStream("c:/addresses.ser"));
    test.readObjects(new FileInputStream("c:/addresses.ser"));
  }

  public void add(AddressBook book, Object[] array, OutputStream _out) {
    try {
      ObjectOutput out = new ObjectOutputStream(_out);

      for (int i = 0; array != null && i < array.length; i += 1) {
        out.writeObject(array[i]);
      }
      out.writeObject(book);
      out.flush();
      out.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public Object[] loadObjects(InputStream in) throws Exception {
    Vector vect = new Vector();

    ObjectInputStream oin = new ObjectInputStream(in);
    while (1 == 1) {
      Object o = null;
      try {
        o = oin.readObject();
        if (o != null) {
          vect.add(o);

        }

      }
      catch (Exception ex) {
        break;
      }
      if (o == null) {
        break;
      }

    }

    return vect.toArray();
  }

  public void readObjects(InputStream in) {
    Vector vect = new Vector();
    try {
      ObjectInputStream oin = new ObjectInputStream(in);
      while (1 == 1) {
        Object o = null;
        try {
          o = oin.readObject();

        }
        catch (Exception ex) {

        }
        if (o == null) {
          break;
        }
        AddressBook book = (AddressBook) o;
        System.err.println("Name :" + book.getName());
        System.err.println("Phone :" + book.getPhone());
        System.err.println("Mail :" + book.getMail());

      }

    }
    catch (Exception e) {
    }

  }

}




_____________________________________________________________________________________

                                    Object Serialization XML Implementation
_________________________________________________________________________________________



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

public class AddressBookXMLTest {
  public AddressBookXMLTest() {
  }

  public static void main(String s[]) throws Exception {
    AddressBookXMLTest test = new AddressBookXMLTest();
    Object[] array = null;
    try {
      array = test.loadObjects(new FileInputStream("c:/addresses.xml"));
    }
    catch (Exception ex) {
    }
    AddressBook book = new AddressBook();
    book.setName(s[0]);
    book.setPhone(s[1]);
    book.setMail(s[2]);
    test.add(book, array, new FileOutputStream("c:/addresses.xml"));
    test.readObjects(new FileInputStream("c:/addresses.xml"));
  }

  public void add(AddressBook book, Object[] array, OutputStream _out) {
    try {
      XMLEncoder out = new XMLEncoder(_out);

      for (int i = 0; array != null && i < array.length; i += 1) {
        out.writeObject(array[i]);
      }
      out.writeObject(book);
      out.flush();
      out.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public Object[] loadObjects(InputStream in) throws Exception {
    Vector vect = new Vector();

  XMLDecoder oin = new XMLDecoder(in);
    while (1 == 1) {
      Object o = null;
      try {
        o = oin.readObject();
        if (o != null) {
          vect.add(o);

        }

      }
      catch (Exception ex) {
        break;
      }
      if (o == null) {
        break;
      }

    }

    return vect.toArray();
  }

  public void readObjects(InputStream in) {
    Vector vect = new Vector();
    try {
  XMLDecoder oin = new XMLDecoder(in);
      while (1 == 1) {
        Object o = null;
        try {
          o = oin.readObject();

        }
        catch (Exception ex) {

        }
        if (o == null) {
          break;
        }
        AddressBook book = (AddressBook) o;
        System.err.println("Name :" + book.getName());
        System.err.println("Phone :" + book.getPhone());
        System.err.println("Mail :" + book.getMail());

      }

    }
    catch (Exception e) {
    }

  }

}
0
 
Giant2Commented:
ramnram,
copy, paste, compile, execute the code I post.
It goes good and solve your problem.

Bye, Giant.
0
 
ramnramAuthor Commented:
let me analyze all ur codes.

just giv me some time.
0
 
objectsCommented:
:)
0
 
sudhakar_koundinyaCommented:
thanks :)
0
 
ramnramAuthor Commented:
U guys deserved it.
0
 
Giant2Commented:
:)
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 12
  • 9
  • 8
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now