In a fairly simple program I wrote, I am saving an object (a game which contains a few other objects) using ObjectOutputStream. My first question is, when I remove "implements Serializable" from any of my classes, a NotSerializableException is NOT thrown. Why not? They are all extending Serializable classes, but shouldn't they themselves have to be Serializable as well?
Another problem I have, which may be related, is that when I read the object back in, I get a java.io.EOFException.
I don't understand why any of these two things are happening. I use the same exact file name for both reading and writing. Why is it hitting the end of the file before it's done?
Here's the writing code:
public void actionPerformed(ActionEvent event)
{
try
{
saver.writeObject(game);
saver.close();
} catch (IOException e)
{
e.printStackTrace();
}
dispose();
}
And here's the reading code:
File file = new File("savedgame.dat");
if (file.exists())
{
try
{
loader = new ObjectInputStream(new FileInputStream(file));
game = (GameBoard) loader.readObject();
loader.close();
}
catch (EOFException ex)
{
ex.printStackTrace();
}
}
else
{
game = new GameBoard();
}
The exception is being thrown on the game = (GameBoard) loader.readObject(); line.
Here's the stack trace:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
If it helps, I'm using many swing objects, but from my research, I'm pretty sure they're all serializable.
Thanks for the help!
readObjectandwriteObjectofGameBoard?readObjectmethod defined on the class you are trying to deserialize?readMethod. But if you had one I would have asked you to include it in your question, as those can be a source of errors. Next question, how soon after writing the file data out do you try and read it back in?