ObjectInputStream available() method doesn't work as expected (Java)

后端 未结 4 1019
时光说笑
时光说笑 2021-01-07 11:00

I\'ve been trying to figure out why a method I\'ve written to read objects from a file didn\'t work and realized that the available() method of ObjectInputStream gave 0 even

相关标签:
4条回答
  • 2021-01-07 11:06

    Although this is not documented clearly I have realized from experience that it has to do with dynamic data. If your class only contains statically typed data, then available() is able to estimate the size. If there are dynamic data in your object, like lists etc, then it is not possible to make that estimation.

    0 讨论(0)
  • 2021-01-07 11:18

    I found some trick! If you still want to use .available() to read all objects to the end, you can add an integer (ex: out.writeInt(0)) before adding each Object (ex: out.writeObject(obj)) when you write to the file and also read integer before reading each Object. So .available() can read byte left on file and won't be crash! Hope it helps you!

    0 讨论(0)
  • 2021-01-07 11:31

    Because, as the javadoc tells, available() returns an estimation of the number of bytes that can be read without blocking. The base InputStream implementation always returns 0, because this is a valid estimation. But whatever it returns, the fact that it returns 0 doesn't mean that there is nothing to read anymore. Only that the stream can't guarantee that at least one byte can be read without blocking.

    0 讨论(0)
  • 2021-01-07 11:31

    The available() method just tells how many bytes can be read without blocking. It's not very useful in regular code, but people see the name and erroneously think it does something else.

    So in short: don't use available(), it's not the right method to use. Streams indicate ending differently, such as returning -1 or in ObjectInputStream's case, throwing an EOFException.

    0 讨论(0)
提交回复
热议问题