So, I've created my own objects and I'm able to stream them to a file. Later, I want to read them in, that part works fine, but how do close the file.
I don't know how many objects there are to read, so I hit the EOF exception and never hit the is.close() line. I can't put the is.close() in EOFException since it's out of scope. Help is greatly appreciated.
I can't put the is.close() in EOFException since it's out of scope.
The normal way to deal with this is to pull the is declaration outside of the try block, and to keep the is assignment inside of it. You should do the same with fin. Or, rather, just close fin, as that will close is as well.
Unlike other Streams and Readers, ObjectInputStream doesn't return a special value when it has reached the end. The correct way to use it is to know ahead of time what you'll be reading. You shouldn't be relying on the exception to tell you when you've reached the end.
Also, your close should always be in a finally block. The standard idiom is this:
You'd normally write a utility class to handle that if/try/catch closing mess for you, so that you can just do something like
And, finally (no pun intended), if you're using Java 7, there's a new language construct called try with resources or something like that, which can automatically do some cleanup for you. I've not used it yet, but it goes something like