End of File

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

  • How does the loop end?
    • When end-of-file is encountered.
  • How should this be handled?
    • With a try/catch structure.

End of File

This loop is the familiar read-until-end-of-file idea which is best done using try{} and catch{} blocks.

DataInputStream  instr;
DataOutputStream outstr;
. . . .
try
{
  int data;
  while ( true )
  {
    data = instr.readUnsignedByte() ;
    outstr.writeByte( data ) ;
  }
}

catch ( EOFException  eof )
{
  outstr.close();
  instr.close();
  return;
}

Almost all of the program is here, but there are more details to handle. The one-byte-at-a-time nature of the loop is very inefficient.

QUESTION 16:

How (in general) can IO be made more efficient in this program?