Java EOFException
DataInputStream.readInt needs four bytes. EOFException signals that the stream ended before the requested value could be read.
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 Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead 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.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
class Main {
public static void main(String[] args) throws Exception {
byte[] packet = {0, 5};
var bytes = new ByteArrayInputStream(packet);
try (var input = new DataInputStream(bytes)) {
System.out.println(input.readInt());
} catch (EOFException incomplete) {
System.out.println("Request the complete record");
}
}
}
Request the complete record
Two bytes cannot supply a four-byte stock count. The application requests another copy instead of guessing the missing bytes.
Decode a complete scanner record
The scanner resends the four-byte stock count after a partial transfer. The inventory worker reads the complete big-endian integer and can now post it to the shelf ledger.
import java.io.DataInputStream;
import java.io.ByteArrayInputStream;
class Main {
public static void main(String[] args) throws Exception {
try (var in = new DataInputStream(new ByteArrayInputStream(new byte[]{0, 0, 0, 5}))) {
System.out.println(in.readInt());
}
}
}
5
The first three zero bytes and final byte five encode the four-byte integer 5.
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.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
new DataInputStream(new ByteArrayInputStream(new byte[]{0,0,0,9})).readInt();
System.out.println("Record complete");
} catch (EOFException problem) {
System.out.println("Request all four bytes");
}
}
}
Record complete
What to watch for
An ordinary read method can signal end of input with -1. DataInputStream reports an incomplete fixed-width value with an exception.