EofException when instantiating ObjectInputStream?

Can anyone explain to me why this would throw an EofException? It really doesn’t make sense to me.


   public void setSaveFile(File saveFile)
	{
		// Assigns the save file
		this.saveFile = saveFile;
		try
		{
			// May create the save file if it does not yet exist
			saveFile.createNewFile();
			
			// Potentially closes streams
			if(!isClosed && in != null)
			{
				in.close();
				out.close();
			}
			
			// Creates new in and out streams
			in = new ObjectInputStream(new FileInputStream(saveFile));    // Decides to get thrown here...
			out = new ObjectOutputStream(new FileOutputStream(saveFile));
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}

Basically, I’m trying to load a save file from the directory “data”. When the file does not exist in this folder, I create a new one. When I do this, however, this exception gets thrown.

java.io.EOFException
	at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
	at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
	at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
	at java.io.ObjectInputStream.<init>(Unknown Source)

This exception does not get thrown when the file already exists. Any suggestions?

An EOFException is thrown when the end of the stream is reached unexpectedly.

I have never used ObjectInputStreams, but I think that they load the header first, and if the file is empty, it reaches the EOS unexpectedly and throws an EOFException.

If the file doesn’t exist, you should not be reading from it.

I don’t know why it is not documented but readObject will throw an EOFException once you try to read past the last object. It is an indicator that you are done reading.

What are you expecting from having a FileInputStream and a FileOutputStream of the same file open at the same time to do?

In FileInputStream it returns -1 at the end and doesn’t throw an exception. Normal behaviour should not throw an exception. I would expect readObject to return null if it has reached end of stream.

I should have commented that I had solved my problem earlier, but better late than never, I suppose. I didn’t realize that OIS read the file header before actually its actual use. I was instantiating an OIS with a FileInputStream pointing to an empty file.

So, in conclusion, I should have created an OIS if, and only if, the file existed and had been written to. :yawn: