• Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I handle End of File in this situtation?  RSS feed

 
Geoff Jefferson
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am using the following construct to read data from a file. Is there
a better way to do this? Currently I'll get the associated IO exception
which doesn't seem to be as elegant as it should be.

 
Geoff Jefferson
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
.....allow me to elaborate.

If I execute the code in the OP within a try block then I should certainly catch any exceptions.
Would it be proper to use the catch to proceed with 'normal' program execution?
If yes, what if some other IO exception occurs?
 
Janeice DelVecchio
Bartender
Posts: 1812
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't use the catch to proceed with normal execution.

I would put the try/catch inside the while loop. That might be what you need to do... that way, when there are no more objects, the application moves forward.

There's probably even a better way than that though.....

Hope that helps,
Janeice
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've experienced this problem before, and it indicates an ill-designed way of storing data. All you need is one extra int before all objects that indicates how many objects there are. This is how most collection classes handle their serialization - first the size is written, then each element. Reading is similar: read the size back first, then read "size" elements.

Should you not know the number of elements you can use booleans between before and after each element. In short, the stream will contain this: (true, object)* false. In normal words, you get 0 or many occurrences of true followed by an object, and the last object is followed by false. Reading is then simple as well:
There is more overhead this way (one int versus n+1 booleans for n objects) but if you don't know n there is little you can do except catch exceptions, and that is nasty, especially if there is data after these objects.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!