• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to close a file  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Saloon Keeper
Posts: 4037
94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, note that you don't close a file, per se. You close Stream or Reader or Writer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!