| Author |
How do I handle End of File in this situtation?
|
Geoff Jefferson
Ranch Hand
Joined: Apr 09, 2009
Posts: 102
|
|
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
Joined: Apr 09, 2009
Posts: 102
|
|
.....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
Saloon Keeper
Joined: Sep 14, 2009
Posts: 1611
|
|
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
|
When you do things right, people won't be sure you've done anything at all.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: How do I handle End of File in this situtation?
|
|
|