4 Replies Latest reply on May 21, 2012 1:13 PM by dadams07

    writing and  Reading serialized Objects

    938503
      [code=java]

      /*hey guys i'm new to java and i have been given an exercise to make a cd collection, write it into a file and read the data back to the program.

      the program is suppose to show you a menu to select from where you can add, delete, view sort, CD's when you add a CD it must be written to a file as an Object and when you want to view CDs or search for a CD the program must read the CD objects from the file they have been written to and must return a cd nam, artist and release date. the code looks like it is writing the Cd to a file but when i try to read (view or search for a cd from the file it gives an error null). so i think i'm note reading the right way.

      thank you for helping .
      */

      import java.io.Serializable;
      public class cd implements Serializable {
           
           //creating attributes
                private String cdname = null;
                private double price = 0.0;
                private String artist =null;
                private int ratings =0;
                private String genre=null;
                private String releaseDate =null;
           // creating an Empty constructor
                
                public cd(){
                
                }

                public cd (String cdname,double price, int ratings, String genre, String artist, String releaseDate){
                this.cdname=cdname;
                this.price=price;
                this.artist=artist;
                this.ratings=ratings;
                this.genre=genre;
                this.releaseDate=releaseDate;
                }
                
                public String getGenre(){
                     return genre;
                }
                public void setGenre(String genre){
                     
                     this.genre =genre;
                }
                public String getArtist(){
                     
                     return artist;
                }
                
                public void setArtist(String artist){
                     this.artist=artist;
                }
                public String getName(){
                return cdname;
                }
                public void setName(String cdname){
                this.cdname = cdname;
                }
                public Double getPrice(){
                return price;
                }
                public void setPrice(double price){
                this.price = price;
                }
                public String getReleaseDate(){
                return releaseDate;
                }
                public void setReleaseDate(String releaseDate){
                this.releaseDate = releaseDate;
                }
                public int getRatings(){
                return ratings;
                }
                public void setRatings( int ratings){
                this.ratings = ratings;

                }

           }

      //............................................................................................................................................................................................................................................


      import java.util.*;

      public class hipHopCollection {

      ArrayList<cd> list = new ArrayList <cd> ();

      EasyIn ei = new EasyIn();

           private cd invoke;
           private int b;
                     
           public void load()
           {
                System.out.println(" You Entered " + b + " To Add A CD ");
                invoke = new cd();
                System.out.println("Please Enter A CD Name ");     
                invoke.setName(ei.readString());
                System.out.println("Please Enter A CD Price");
                invoke.setPrice(ei.readDouble());
                System.out.println("Please Give Ratings For The CD");
                invoke.setRatings(ei.readInt());
                System.out.println("Please Enter A CD release date ");
                invoke.setReleaseDate(ei.readString());
                System.out.println("Please Enter artist Name ");
                invoke.setArtist(ei.readString());
                System.out.println("Please Enter A CD Genre ");
                invoke.setGenre(ei.readString());
                list.add(invoke); // trying to add cd information to invoke.
                
                
           }// end of load
           
      // The following method should return the Object variable invoke that holds the cd INFO

           public Object getInvoke()
           {
           return invoke;
           }
      //........................................................................................
           
           public int getB()
           {
           return b;
           }
                
           public void setB()
           {
           b=ei.readInt();
           }     
           
           public void menu(){
                System.out.println("......................................................... ");
                System.out.println("Hi There Please Enter A Number For Your Choice");
                System.out.println(" Pess >>");
                System.out.println("1 >> Add A CD");
                System.out.println("2 >> View List Of CD's");
                System.out.println("3 >> Sort CD's By Price");
                System.out.println("4 >> Search CD By Name");
                System.out.println("5 >> Remove CD(s) By Name");
                System.out.println("0 >> Exit");
                System.out.println(".........................................................");
                System.out.print("Please Enter Chioce >> ");     
                
           }// end of menu
           
           public void GoodBye()
           {
                System.out.println(" You Entered " + b + " To exit Good_bye" );
                System.exit(0);
           }//end of GoodBye
           
           public void PriceSort()
           {
                System.out.println(" You Entered " + b + " To Sort CD(s) By price ");
                Collections.sort(list, new SortByPrice());
                for(cd s : list)
                System.out.println(s.getName() + ": " + s.getPrice());
           }// end of PriceSort


           public void NameSearch()
           {
                     System.out.println(" You Entered " + b + " To Search CD(s) By Name ");
                     System.out.println("Please Enter The Name Of The CD You Are Searching For " );
                     String search = ei.readString();
                     for(int i=0; i<list.size();i++){
                     if(search.equalsIgnoreCase(list.get(i).getName() )){
                     System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );

           }     
           }
      }//end of NameSearch
           
           public void ViewList()
           {
                     System.out.println(" You Entered " + b + " To view CD(s) By Name ");
                     for(int i=0; i<list.size();i++)
                     {
                     System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
                     }
           }// end of ViewList
           
           public void DeleteCd()
           {
                     System.out.println(" You Entered " + b + " To Delete CD(s) By Name ");
                     System.out.println("Please Enter The Name Of The CD You Want to Delete ");
                     String search = ei.readString();
                     for(int i=0; i<list.size();i++)
                     {
                     if(search.equalsIgnoreCase(list.get(i).getName() ))
                     {
                     System.out.println(list.get(i).getName());
                     list.remove(i);
                     }
                     }
           }// end of DeleteCD
           //....................................................................................
           public static void main(String[] args) {
           //creating an Instance of EasyIn by object ei. Easy in is a Scanner class for reading
                EasyIn ei = new EasyIn();


                ArrayList<cd> list = new ArrayList <cd> (); // creating an array cd list
                
                hipHopCollection call = new hipHopCollection();
                
                ReadWrite rw = new ReadWrite();
                     while (true){
                     call.menu();
                     call.setB();
                     //b = ei.readInt();
                     if(call.getB()==0)
                     {
                          call.GoodBye();
                     }
                     if(call.getB()==1)
                     {
                          call.load();
                          rw.doWriting();// trying to write the cd object to a file
                     }
                     if(call.getB()==2)
                     {
                     rw.doReading();// trying to read the cd object from a file
                     //call.ViewList();
                     }
                     if(call.getB()==3)
                     {
                     call.PriceSort();
                     }
                     if(call.getB()==4)
                     {
                          call.NameSearch();
                     }
                     if(call.getB()==5)
                     {
                          call.DeleteCd();
                     }
                     
                     
           }// end of while
      }// end of main
      }// end of class
      //.....................................................................................................................................................................................................................

      // importing all the packages that we will use
      import java.io.ObjectInputStream;
      import java.io.FileInputStream;
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.ObjectOutputStream;
      import java.io.OutputStream;
      import java.io.Serializable;

      public class ReadWrite {
      // these are all the attributes
           private String FileName ="CdCollections.dat";     
           private OutputStream output;
           private ObjectOutputStream oos;
           private FileOutputStream fos;
           private File file;
           private FileInputStream fis;
           private ObjectInputStream ois;
           
           //creating an empty constructor
           public ReadWrite()
           {
           // we could initialise all the attributes inside this empty constructor
           }
           
           //creating a constructor with arguments of a file name.
           public ReadWrite(File file)
           {
                
                this.file=file;
                
                try
                {
                     //Use a FileOutputStream to send data to a file called CdCollections.dat
                     fos = new FileOutputStream(file,true);
                     /*
                     Use an ObjectOutputStream to send object data to the
                     FileOutputStream for writing to disk.
                     */
                     oos = new ObjectOutputStream (fos);
                     fis=new FileInputStream(file);
                     ois = new ObjectInputStream(fis);
                     
                }
                catch(FileNotFoundException e)
                {
                     System.out.println("File Not Found");
                }
                catch(IOException a)
                {
                     System.out.println(a.getMessage());
                     System.out.println("Please check file permissions of if file is not corrupt");
                }
                
           }// end of the second constructor
           
           //the following lines of code will be the accessors and mutators
      //........................................................................................................
           
           /**
           * @return the output
           */
           public OutputStream getOutput() {
                return output;
           }

           /**
           * @param output the output to set
           */
           public void setOutput(OutputStream output) {
                this.output = output;
           }

           /**
           * @return the objStream
           */
           public ObjectOutputStream getOos() {
                return oos;
           }

           /**
           * @param objStream the objStream to set
           */
           public void setObjStream(ObjectOutputStream objStream) {
                this.oos = oos;
           }
           public File getFile() {
                return file;
           }

           public void setFile(File file) {
                this.file = file;
           }

           public FileInputStream getFis() {
                return fis;
           }

           public void setFis(FileInputStream fis) {
                this.fis = fis;
           }

           public ObjectInputStream getOis() {
                return ois;
           }

           public void setOis(ObjectInputStream ois) {
                this.ois = ois;
           }
           // the following lines of code will be the methods for reading and writing
      /*........................................................................................

      the following method doWriting will write data from the hipHopCollections source code.
      that will be all the cd information.

      Pass our object to the ObjectOutputStream's
      writeObject() method to cause it to be written out
      to disk.
      obj_out.writeObject (myObject);

      ........................................................................................*/
           public void doWriting()
           {
                hipHopCollection call = new hipHopCollection();
                
      //creating an Object variable hold that will hold cd data from hipHopCollections invoke
                
                Object hold = call.getInvoke();// THI COULD BE THE PART WHERE I MADE A MISTAKE
                
                ReadWrite stream = new ReadWrite (new File(FileName));
                
                try
                {
                
                /*
                Pass our object to the ObjectOutputStream's
                writeObject() method to cause it to be written out to disk.
                stream.getOos().writeObject(hold);
                */
                     stream.getOos().writeObject(hold);
                     stream.getOos().close();
                     System.out.println("Done writing Object");
                }
                
                catch (IOException e)
                {
                     System.out.println(e.getMessage());
                     System.out.println("Program Failed To Write To The File");     
                }
                finally
                {
                     System.out.println("The program Has come To An End GoodBye");
                }
                
           }// end of method DoWriting
           
      /*........................................................................................

      The following method is for reading data from the file written by the above method named
      DoWriting
      .........................................................................................*/     
      // PLEASE NOT THIS IS THE METHOD THAT GIVES ME NULL EXCEPTION
           public void doReading()
           {
           ReadWrite read = new ReadWrite(new File(FileName));
                try{
                     //System.out.println("I AM NOW INSIDE THE TRY TO READ");
                     Object obj = read.getOis().readObject();
                     System.out.println("tried reading the object");
                     cd c = (cd)obj; // trying to cast the object back to cd type
                          
                     System.out.println("I have typed cast the Object");               
                     System.out.println(c.getName());
                     System.out.println(c.getGenre());
                     System.out.println(c.getArtist());
                     System.out.println(c.getPrice());
                     System.out.println(c.getRatings());
                     System.out.println(c.getReleaseDate());
                     read.getOis().close();
                     
                     
                }
                catch(ClassNotFoundException e)
                {
                System.out.println(e.getMessage());
                System.out.println("THE CLASS COULD NOT BE FOUND");
                }
                catch(IOException e)
                {
                System.out.println(e.getMessage());// null
                System.out.println("WE COULD NOT READ THE DATA INSIDE THE FILE");
                }
           }//end of method doReading
      }// end of class ReadWrite