Scala EOFException
DataInputStream raises EOFException when a fixed-width integer is only partly available.
A simple example
EOFException
- Start with One available byte
- Do this Try to read a complete two-byte field
- Result One byte is missing
Syntax
input.readInt()
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonRead a stock count from a short record
A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.
import java.io.DataInputStream
import java.io.ByteArrayInputStream
import java.io.EOFException
object Lesson {
def main(args: Array[String]): Unit = {
val input = new DataInputStream(new ByteArrayInputStream(Array[Byte](0, 5)))
try {
println(input.readInt())
} catch {
case problem: EOFException =>
println("Request the complete record")
}
}
}
Request the complete record
The two-byte transfer falls short of the four bytes required for a stock count.
Decode a complete gate count
A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
Detect a cut-off meter record
A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
What to watch for
Check the binary format before decoding. A four-byte integer cannot be recovered from two bytes alone.