Reading until EOF
An unsigned integer is zero or postive.
In Java (regardless of computer platform) primitive type byte
holds an integer in the range -128 to +127.
An unsigned byte holds values 0 to +255,
so something larger than datatype byte is needed.
Datatype int is returned because it is used more
often than the other integer types.
Most methods of DataInputStream throw
an EOFException when the end of a file
is reached.
Let us work on a program that uses this
idea to read integers until
end of file.
The loop of the program looks like this:
try
{
while ( true )
sum += instr.readInt();
}
catch ( EOFException eof )
{
System.out.println( "The sum is: " + sum );
instr.close();
}
The while loop keeps going until readInt()
hits the end of the file.
Then it throws an exception and execution jumps out of the
loop to the catch{} statement.
|