Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Appending Objects to a textfile(using ObjectOutputStream)

 
Brian Cummins
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I am pretty new to java and im having a problem with my program. My problem is appending objects to a file. When my program is first opened i can save books to the file and display them. However, when i exit and reopen the project i can only display objects previously added even after i save new objects to the file. i think the problem is that the ObjectoutputStream is writing a new header to the file each time it is opened. Is there any way to get past this?



objOutputBook = new FileOutputStream("Book.txt",true);
objSaveBook = new ObjectOutputStream(objOutputBook);


Book bookCurrent = new Book(txtId.getText(), txtTitle.getText(),txtAuthor.getText(),
txtPublisher.getText(),txtGenre.getText(), Float.parseFloat(txtPrice.getText()), Integer.parseInt(txtQty.getText()));

objSaveBook.writeObject(bookCurrent);
}
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object Serialization FAQ:

# Why can't a file that contains multiple appended ObjectOutputStreams be deserialized by one ObjectInputStream?

Using the default implementation of serialization, there must be a one-to-one mapping between ObjectOutputStream construction and ObjectInputStream construction. ObjectOutputStream constructor writes a stream header andObjectInputStream reads this stream header. A workaround is to subclass ObjectOutputStream and override writeStreamHeader(). The overriding writeStreamHeader() should call the super writeStreamHeader method if it is the first write to the file and it should call ObjectOutputStream.reset() if it is appending to a pre-existing ObjectOutputStream within the file.
 
Brian Cummins
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the advice. I couldnt get it to work though. I ended up using an arraylist and using the objectOutputStream (without append) to write it to the file. Its much easier that way and its easier to add, edit and delete... jus thought you'd like to know in case anyone else is having the same problems.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!