Reputation: 97
I am currently doing serialization in JAVA, As of now I have gotten the serializing and de-serializing working correctly. eg If I make a film in the program, close the program and then reopen the program the film will still be there. My problem is, even though all the code works and the serializing works correctly when I run the program I get this error as seen below.
Here you can see my program running and it showing the exception
Here is the code where the exception is pointing to
public void readRecordsFromFile()
{
Video v = null;
try
{
FileInputStream fileIn = new FileInputStream("PrintOut.dat");
ObjectInputStream in = new ObjectInputStream(fileIn);
while((v = (Video)in.readObject()) != null)
{
videos.add(v);
}
//videos=(ArrayList<Video>)in.readObject();
fileIn.close();
in.close();
}
catch(IOException i)
{
System.out.println("IO Exception");
i.printStackTrace();
return;
}
catch(ClassNotFoundException m)
{
System.out.println("Class Not Found Exception");
m.printStackTrace();
return;
}
}
And in particular it points to the line
while((v = (Video)in.readObject()) !=null)
Is there a way to remove the exception? The fact that my program runs fine even with the exception makes me believe that it maybe isn't that important but I feel it would be good practice to remove the exception.
Any help would be appreciated and if any of the other code is required just let me know, Thanks in advance, Jason
Upvotes: 0
Views: 364
Reputation: 3527
EOFException means you hit the end of the file and there's nothing to really deal with that. What I would recommend is adding a new catch for the EOFException to keep the error from showing up in your console. I would also move the close() calls to a finally block - so something like this:
public void readRecordsFromFile()
{
Video v = null;
try
{
FileInputStream fileIn = new FileInputStream("PrintOut.dat");
ObjectInputStream in = new ObjectInputStream(fileIn);
while((v = (Video)in.readObject()) != null)
{
videos.add(v);
}
//videos=(ArrayList<Video>)in.readObject();
}
catch(IOException i)
{
System.out.println("IO Exception");
i.printStackTrace();
return;
}
catch(ClassNotFoundException m)
{
System.out.println("Class Not Found Exception");
m.printStackTrace();
return;
}
catch(EOFException eofe)
{
// Don't print anything, we just don't want the error blowing up in the regular output.
return;
}
finally
{
// Guarantee that the streams are closed, even if there's an error.
fileIn.close();
in.close();
}
}
Upvotes: 1
Reputation: 20520
There's no really clean way to work out when the ObjectInputStream
is going to hit the buffers.
Your best strategy is to start by writing an integer at the beginning to say how many objects you're going to write. Then, when you read objects back, you start by reading this integer in; then you read that many objects from the stream.
Upvotes: 3