In the following code i am trying to write a serialized object to a sequential access file. This code uses another class "Account" contained in a package which implements "Serializable" interface and contains 4 instance variables viz. acc_no, first, last and balance for maintaining record of an individual along with his first name, last name, account no and balance. Now the problem i am facing is that when i add 2 or more records i am able to write only the first record two or more times and the second record and successive is not saved i.e for the following entry when the code is executed :
Enter in the following order :
Account number, first name, last name, balance : 100 russel crowe 1000000
200 tom hanks 3000000
300 will smith 4000000
When i read the above data from the file by deserializing (code not mentioned here) it following output is observed :
100 russel crowe 1000000.0
100 russel crowe 1000000.0
100 russel crowe 1000000.0
However, when i create a new Account object for every record entry i get the expected output.
So, my question is why is that "record" object with "writeObject(record)" method retains only the first entry? And why is it always necessary to create a new Account object to obtain expected output? Sorry, my doubt has gone a bit lengthy. Hope i have successfully conveyed what i wanted to ask.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.NoSuchElementException;
import java.util.Scanner;
import packtest.account.Account;
public class SerizbleTest {
private static ObjectOutputStream obj;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Account record = new Account();
System.out.printf("Enter in the following order :%nAccount number, first name, last name, balance : ");
try {
obj = new ObjectOutputStream(new FileOutputStream("sertest1.ser"));
while (in.hasNext()) {
//record = new Account();
record.setAccount(in.nextInt());
record.setFirst(in.next());
record.setLast(in.next());
record.setBalance(in.nextDouble());
//System.out.println(record.getAccount());
obj.writeObject(record);
}
}
catch (NoSuchElementException e) {
System.out.println("Invalid input entered !!!");
in.nextLine(); //discarding the input
}
catch (FileNotFoundException e) {
System.out.println("File Does not Exist");
in.close();
//obj.close();
System.exit(1);
}
catch (IOException e) {
System.out.println("IOException occurred !!!");
}
}
}