问题
I have created a program which registers members for a library system. To store the data i have used text files and to read/write i implemented serialization.
My problem is when i register one member and try to register another member, the second member records won't get saved. To append writing to the file i used the keyword "true" as well.
Here is what i have done:
//Am writing the object to a file
public void RegisterMembers(Members object) {
try{
FileOutputStream write=new FileOutputStream("Memberships.txt",true);
ObjectOutputStream writeFile=new ObjectOutputStream(write);
writeFile.writeObject(object);
writeFile.flush();
writeFile.close();
}catch(Exception e){
Frame frame=new Frame();
JOptionPane.showMessageDialog(frame,"Storage file not found");
}
}
//Method to read from the file
public void readMemberships() throws FileNotFoundException, IOException, ClassNotFoundException{
Person object;
FileInputStream read=new FileInputStream("Memberships.txt");
ObjectInputStream readFile=new ObjectInputStream(read);
object=(Person)readFile.readObject();
System.out.println(object);
}
//Here is a piece of code which is in the gui frame which i implemented
Members newMember=new Members(firstName,initials,birthDay,birthMonth,birthYear,Gender,memberid,address,tele,membershipType,paymentType);
newMember.RegisterMembers(newMember); //calls the 2 methods
newMember.readMemberships();
What seems to be the error here? I want it to append when writing.
Thank you for your time.
回答1:
I think that the topic I created (It is solved now) is what you are looking for.
"You can't append to an existing file created with an ObjectOutputStream, at least not without effort. There is a trick somewhere about extending ObjectOutputStream and overriding the `writeStreamHeader() method so as not to write the stream header the second time (...)" - answered by EJP
Please have look for my topic here:
- Write and read multiple objects to file.
You can also check the link below
- Appending to an ObjectOutputStream
It is what you were looking for?
来源:https://stackoverflow.com/questions/18224333/writing-objects-to-file-while-appending