-2

Im struggling to get my head around saving an array to a file and then reading it back in to the same array that it was saved from.

the code for Person is

    import java.io.*;

public class Person implements Serializable
{
        protected String name;
        protected char gender;
        protected Date dateOfBirth;
        protected String address;
        protected String natInsceNo;
        protected String phoneNo;

        public Person()
        {
            this("", 'N' , new Date());
        }

        public Person (Person other)
        {
            // Create a clone from Person other
            //TO DO
        }

        public Person (String aName, char sex, Date dob)
        {
            name = aName;
            gender = sex;
            dateOfBirth = dob;
            address = "";
            natInsceNo = "" ;
            phoneNo = "";

        }

        public void setName(String aName)
         {
               //Setter method to alter the Person aName string
                name = aName;
         }

         public void setAddress(String addr)
         {
               //Setter method to alter the Person address string
                address = addr;
         }
         public void setNatInsNo(String ins)
         {
               //Setter method to alter the Person national insurance number
                natInsceNo = ins;
         }

         public void setPhone(String phone)
         {
               //Setter method to alter the Person phone number
                phoneNo = phone;
         }

         public String getName()
         {
               //Getter method to return the Person name String
             return name;

         }
         public String getAddress()
         {
               //Getter method to return the Person address String
             return address;

         }
         public String getNatInsNo()
         {
               //Getter method to return the Person national insurance String
             return natInsceNo;

         }
        public String getPhone()
        {
               //Getter method to return the Person phone number
            return phoneNo;
        }

        public boolean equals(Person other)
        {
        // return true if name, dateOfBirth and national insurance number are same 

            return false;
        }

        public String toString()
        {
               //Override the toString() method of the Object class
                String output= "";
                output = "Name: " + name + ", Gender: " + gender+ ",  Date Of Birth: " + dateOfBirth +", National Insurance No "+natInsceNo+"";
            return output;      
        }

}

The code for my employee is

    import java.awt.List;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;

import javax.swing.JOptionPane;
public class Store implements Serializable
{
private static int MAXSIZE; // holds the size of the array
private static int count; // keeps count of number of  employees stored in array 
Person list[];
static String fileName = "Employee.txt";


        public void save(Person testStore) throws IOException{
            try{
                FileWriter fr = new FileWriter(fileName);
                PrintWriter pr = new PrintWriter(fr);
                for(int i=0; i<Store.getCount(); i++)
                {
                    pr.println(list[i]);
                }
                pr.close();
            }
            catch(IOException e){
                String message = "problem Writing to file";
                JOptionPane.showMessageDialog(null,  message, null, JOptionPane.ERROR_MESSAGE);
            }
        }

        public void readFile() throws IOException {
            BufferedReader CSVFile = new BufferedReader(new FileReader(fileName));
            String dataRow = CSVFile.readLine();
            while (dataRow !=null){
                String[] dataArray = dataRow.split(",");
                for (String item:dataArray){
                    System.out.print(item);
                    //int i=0;
                    //String word = item;
                    //list[i]=item;
                }

                System.out.println();
                dataRow = CSVFile.readLine();
            }
        }






        public Store(int size)
        {
            //Constructor which allow the size of the store to be specified
            list = new Person[size];
            MAXSIZE = size;
            count=0;
        }

        public static void setFileName(String fileNameIn){
            fileName = fileNameIn;          
        }

       public static int getCount()
       {
             //Getter method to return the number of elements currently in store
            //To do
           return count;
       }
       public static boolean isFull()
       {
             //Returns true if no more space in store
            //To do
           return count == MAXSIZE;
       }
       public Store()
       {
             //Default constructor
            this(0);
       }

       public Store(Store s)
       {
             //Create a Store from another Store s
            //To do
       }
       public void add(Employee e)
       {
           list[count++] = e;
       }


       public void displayAll()
       {
           //display the contents of store on the screen
           for (int i = 0; i< count; i++)
               System.out.println(list[i]); 
        }    


}

the code for my save is

Person list[]; static String fileName = "Employee.txt";

    public void save(Person testStore) throws IOException{
        try{
            FileWriter fr = new FileWriter(fileName);
            PrintWriter pr = new PrintWriter(fr);
            for(int i=0; i<Store.getCount(); i++)
            {
                pr.println(list[i]);
            }
            pr.close();
        }
        catch(IOException e){
            String message = "problem Writing to file";
            JOptionPane.showMessageDialog(null,  message, null, JOptionPane.ERROR_MESSAGE);
        }
    }

Im sorry if the code is a little messed up and not very structured.

  • 1
    Where you having problem? – Achintya Jha Feb 05 '13 at 15:53
  • and what is the problem? – Dan Feb 05 '13 at 15:53
  • 1
    Why do give a parameter person to the save function if you're not using it? And in you're readfile method you should make an object from Person using the string items. Then put that object into the list – David Maes Feb 05 '13 at 15:59
  • btw. closing Streams ['Example'](http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html) is important. ['Example Java7'](http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html) – oliholz Feb 05 '13 at 16:05

1 Answers1

1

Use ObjectOutputStream to serialize Object state into text file and use ObjectInputStream to get it back.

ObjectOutputStream output = new ObjectOutputStream(
                            new FileOutputStream(fileName));
output.writeObject(Store);
output.close();

and

ObjectInputStream input = new ObjectInputStream(
                            new FileInputStream(fileName));
ArrayList<Person> store = (ArrayList<Person>)input.readObject();
input.close();
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • When i use serialization my text file it saves to when i open it in file explorer reads ¬í ur [LPerson;™sOÈÄ—Î xp dsr Employeeár|`Ûžç F salaryL idt Ljava/lang/String;L jobTitleq ~ L startt LDate;xr PersonÏÉÒ§ C genderL addressq ~ L dateOfBirthq ~ L nameq ~ L natInsceNoq ~ L phoneNoq ~ xp Mt sr DateÖk®Å´u¶a I dayI monthI yearxp Ýt Nathant fct cCj t 1t dfvsq ~ Ýpppppppppppppppppppppppppppppppppp Im not sure if that is how it should be or no, also when using serilaztion to read the file in it has an error of 'code' [LPerson; cannot be cast to java.util.ArrayList 'code' – user2043723 Feb 06 '13 at 10:44
  • When you persist object it will write in byte array. tell me one thing is `Store` arraylist Object ? – Subhrajyoti Majumder Feb 06 '13 at 10:54
  • Store is a class and list is arraylist of type person which is also aclass. declared as Person list[]; – user2043723 Feb 06 '13 at 11:01
  • `Store store = (Store)input.readObject();` see what Object type you persist read and cast in same type. if that is `Person` and cast it to person. – Subhrajyoti Majumder Feb 06 '13 at 11:02
  • ArrayList list = (ArrayList)input.readObject(); – user2043723 Feb 06 '13 at 11:05
  • Im stumped, is there away to upload my project to see how i have implemented it and suggest afew amendments? – user2043723 Feb 06 '13 at 11:09