11

The following code produces an EOFException. Why is that?

public static Info readInfoDataFromFile(Context context) {
    Info InfoData = null;
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    Object object = null;

    if (context.getFileStreamPath("InfoFile.dat").exists()) {
        try {
            fis = context.openFileInput("InfoFile.dat");
            ois = new ObjectInputStream(fis);
            Object temp;
            try {
                // here it throws EOF exception in while loop 
                while ((temp = ois.readObject()) != null) {
                    object = temp;
                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            } catch (EOFException eof) {
                eof.printStackTrace();
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

StackTrace:

03-07 14:29:01.996: WARN/System.err(13984): java.io.EOFException
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.DataInputStream.readByte(DataInputStream.java:131)
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.nextTC(ObjectInputStream.java:628)
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:907)
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
03-07 14:29:01.996: WARN/System.err(13984):     at 
Neuron
  • 5,141
  • 5
  • 38
  • 59
AZ_
  • 21,688
  • 25
  • 143
  • 191
  • 2
    Javadoc : `Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true` – Michaël Mar 07 '11 at 09:33
  • yeah I have already read it but how to avoid it? – AZ_ Mar 07 '11 at 09:36

5 Answers5

9

Depends on how many objects your file contains. If it has only one object, you can deserialise in one step.

try {
    Object temp = ois.readObject();
}
catch(Exception e) {
    //handle it
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
adarshr
  • 61,315
  • 23
  • 138
  • 167
  • 7
    @Aizaz: why do you expect `readObject()` to return `null` at the end of the file? It doesn't, it's specified to always return the object or throw an exception. So unless you've explicitly serialized `null`, you shouldn't expect `readObject()` to return `null`. – Joachim Sauer Mar 07 '11 at 09:37
  • then how to detect at we are at end of file? I mean how to avoid EOF exception? – AZ_ Mar 07 '11 at 10:53
  • 1
    @Aizaz - readObject() will read the entire file at once and deserialize it for you. Just make sure that you call it only once and not in a loop. – adarshr Mar 07 '11 at 10:55
  • @adarshr Tank you sooooooooooooooo much dear friend. – AZ_ Mar 07 '11 at 11:54
  • 2
    @adasrshr That is misleading - readObject will deserialize one object from the file. If the file contained only one object, then you are correct. If however it contained more than one object, you would need to call readObject() more than once. – AndyT Mar 08 '11 at 09:33
  • @AndyT - You're mistaken! Please read the [Sun's Serialization FAQs](http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp#appendSerialStream) – adarshr Mar 08 '11 at 10:53
  • 2
    @adasrshr Have a look here: http://download.oracle.com/javase/1.4.2/docs/api/java/io/ObjectInputStream.html and you'll see an example of reading multiple objects from a stream. The FAQ appears to refer to limitations of the WriteStream object and contradicts the current Java API docs. – AndyT Mar 08 '11 at 14:22
8

First of all, readObject() only returns null if you wrote null to the stream when creating it. If there is no more data in the stream, it will throw an EOFException.

If you don't expect the EOF, the reason is probably that the stream is corrupt. This can happen if you forget to close it after writing data to it.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • then how to detect at we are at end of file? I mean how to avoid EOF exception? – AZ_ Mar 07 '11 at 10:53
  • 5
    @Aizaz: The EOFException tells you that. Checked exception are meant to be caught and examined for control flow. They aren't errors but additional return codes. Sometimes. If used correctly. Which is not the case for most IOExceptions. But correct for EOFException. ... Ahem. Another solution is to write the number of objects into the stream before the objects, so you can loop a known number of times. Or put the objects in a container like a list or an array and load the container instead. – Aaron Digulla Mar 07 '11 at 13:18
  • I think this is the correct answer: @Aizaz - readObject() will read the entire file at once and deserialize it for you. Just make sure that you call it only once and not in a loop. – adarshr 18 hours ago – AZ_ Mar 08 '11 at 05:25
  • @Aizaz: This is only true when you write just one object into the file. Your code to *read* the stream must match the code that *writes* the stream. If you write 5 objects, you must read five. If you write a list with 5 objects, you must call `readObject()` once (because the list will handle the 5 objects for you). – Aaron Digulla Mar 08 '11 at 09:19
5

I had the same mysterious EOFException and it was only the path of the Object Class to send across the ObjectOutputStream to the ObjectInputStream. They must have the same path (same package name and, of course, same class name).

Neuron
  • 5,141
  • 5
  • 38
  • 59
Alex
  • 51
  • 1
  • 1
2

The definition of readObject() on ObjectInputStream doesn't specify that it will return null when the end of stream is reached. Instead an exception is thrown if you attempt to read an additional object beyond the end of the file.

Neuron
  • 5,141
  • 5
  • 38
  • 59
AndyT
  • 1,413
  • 9
  • 11
  • then how to detect at we are at end of file? I mean how to avoid EOF exception? – AZ_ Mar 07 '11 at 10:54
  • Either store information in the file that tells you how many objects to expect, or handle the EOF exception properly. Remember that exceptions are not necessarily 'failures', but can be used as a way to propagate state changes up though the stack. – AndyT Mar 07 '11 at 10:58
0

I received this error because using OutputStream.write() to write an int and InputStream.readInt() to read one.

However, OutputStream.write writes a byte according to the documentation (put accepts an int as parameter), so instead, I needed to use OutputStream.writeInt.

Matthias
  • 12,053
  • 4
  • 49
  • 91