How to prevent InputStream.readObject() from throwing EOFException?

孤人 提交于 2019-11-29 03:54:40

EOFException means you are trying to read past the end of the file. Normally you don't have any way of knowing whethere there are more objects to read, other than trying it, so you shouldn't regard EOFException as a problem in the first place. If it is thrown in a situation where you think you know there are more objects in the file, e.g. when you have prefixed an object count to the file, it indicates a problem with the code that wrote the file, or possible corruption of the file itself. Another example is a zero length file that shouldn't be zero length. Whatever the problem is, it can't be solved by the reading end, it is already too late.

I cannot see any problem with the writing and reading of the file.

So my best guess is that the problem is at the file level. For example:

  • you could be writing one file and reading a different one, or
  • you could be reading the file before the file write completes, or
  • something else could be clobbering the file in between the running of your write code and read code.

I suggest that you add some tracing code that uses File.length() to find out what the file size is after you've written it and before you read it.


A couple of other possibilities:

  • the writer and reader code is using different versions of MyClass (or a dependent class) with incompatible representations and the same serialVersionId values, or

  • you could be using custom readObject and writeObject methods that are incompatible.

In my case, EOF Exception was solved by ensuring the read and writes to the file were thread safe. Like Stephen C answered above, if you try to write to a file which you also are trying to read from say from another thread, you may be stepping on the ObjectInputStream which is going to throw EOF Exception in this case.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!