Solved

appeding objects in file using ObjectOutputStream

Posted on 2004-10-03
41
257 Views
Last Modified: 2010-03-31
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
Comment
Question by:ramnram
  • 12
  • 9
  • 8
  • +3
41 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>> i tried to append objects but i couldn't.

Your class should implement Serializable interface
0
 
LVL 2

Expert Comment

by:fredwangus
Comment Utility
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
 

Author Comment

by:ramnram
Comment Utility
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
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
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
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
In your case you must close the file before you read.
0
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
put
oos.flush();
oos.close();
before opening again the file.
0
 
LVL 2

Expert Comment

by:fredwangus
Comment Utility
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
 

Author Comment

by:ramnram
Comment Utility

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
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
put oos.flush();
         aBook.addAddress(oos,name,phone,email);
          oos.flush();<---------------------insert here.
          oos.close();
0
 

Author Comment

by:ramnram
Comment Utility
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
 
LVL 2

Expert Comment

by:fredwangus
Comment Utility
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
 

Author Comment

by:ramnram
Comment Utility
hi giant2,
  Thanks 4 ur suggestion. but still(after putting flush(); in that place) i'm getting the same problem.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 

Author Comment

by:ramnram
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 
LVL 92

Accepted Solution

by:
objects earned 100 total points
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
> 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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
 

Author Comment

by:ramnram
Comment Utility
Sudhakar,
 Thanks for ur lot of suggestions, but we needed simple core java program.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>>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
 
LVL 2

Expert Comment

by:fredwangus
Comment Utility
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
 
LVL 12

Assisted Solution

by:Giant2
Giant2 earned 50 total points
Comment Utility
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
 

Author Comment

by:ramnram
Comment Utility
fredwangus,
  But, I wanted records to be permenant in the file.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
did u try the changes I posted, they should meet your needs.

0
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
try my code.
Copy and paste.
Bye, Giant.
0
 
LVL 2

Assisted Solution

by:fredwangus
fredwangus earned 50 total points
Comment Utility
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
 
LVL 14

Assisted Solution

by:sudhakar_koundinya
sudhakar_koundinya earned 50 total points
Comment Utility
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
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
ramnram,
copy, paste, compile, execute the code I post.
It goes good and solve your problem.

Bye, Giant.
0
 

Author Comment

by:ramnram
Comment Utility
let me analyze all ur codes.

just giv me some time.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
:)
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
thanks :)
0
 

Author Comment

by:ramnram
Comment Utility
U guys deserved it.
0
 
LVL 12

Expert Comment

by:Giant2
Comment Utility
:)
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now