Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FileInputStream ObjectInputStream reaches end of file EOF

Tags:

I am trying to read the number of line in a binary file using readObject, but I get IOException EOF. Am I doing this the right way?

    FileInputStream istream = new FileInputStream(fileName);     ObjectInputStream ois = new ObjectInputStream(istream);      /** calculate number of items **/     int line_count = 0;     while( (String)ois.readObject() != null){                     line_count++;     } 
like image 858
user69514 Avatar asked Apr 12 '10 23:04

user69514


People also ask

Does FileInputStream need to be closed?

close() method. After any operation to the file, we have to close that file.

Which exception is thrown by FileInputStream?

The FileInputStream read() method throws a java. io. IOException if for some reason it can't read from the file. Again, the InputFile class makes no attempt to catch or declare this exception.

How does FileInputStream work in Java?

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .


1 Answers

readObject() doesn't return null at EOF. You could catch the EOFException and interpret it as EOF, but this would fail to detect distinguish a normal EOF from a file that has been truncated.

A better approach would be to use some meta-data. That is, rather than asking the ObjectInput how many objects are in the stream, you should store the count somewhere. For example, you could create a meta-data class that records the count and other meta-data and store an instance as the first object in each file. Or you could create a special EOF marker class and store an instance as the last object in each file.

like image 175
erickson Avatar answered Sep 21 '22 13:09

erickson