I had the same problem today. Although the question is quite old, the problem remains and there was no clean solution provided. Ignoring EOFException
should be avoided as it may be thrown when some object was not saved correctly. Writing null obviously prevents you from using null values for any other purposes. Finally using available()
on the objects stream always returns zero, as the number of objects is unknown.
My solution is quite simple. ObjectInputStream
is just a wrapper for some other stream, such as FileInputStream. Although ObjectInputStream.available ()
returns zero, the FileInputStream.available will return some value.
FileInputStream istream = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(istream);
/** calculate number of items **/
int line_count = 0;
while( istream.available() > 0) // check if the file stream is at the end
{
(String)ois.readObject(); // read from the object stream,
// which wraps the file stream
line_count++;
}