readInt()

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:

DataInputStream

readInt()

Here is a program that reads four integers, adds them up, and writes the sum (as characters) to the monitor. It expects a data file intData.dat.

import java.io.*;
class ReadInts
{
 public static void main ( String[] args ) 
 {
   String fileName = "intData.dat" ;  
   long sum = 0;

   try
   {      
     DataInputStream instr = 
       new DataInputStream(
         new BufferedInputStream(
           new FileInputStream( fileName ) ) );

     sum += instr.readInt();
     sum += instr.readInt();
     sum += instr.readInt();
     sum += instr.readInt();
     
     System.out.println( "The sum is: " + sum );
     instr.close();
   }
   catch ( IOException iox )
   {
     System.out.println("Problem reading " + fileName );
   }
 }
}

The method readInt() grabs four bytes from the input stream and returns them as an int. That value can be used in arithmetic without conversion.

QUESTION 3:

Say that the file "intData.dat" was written by the following lines:

     out.writeInt(  0 );
     out.writeInt(  1 );
     out.writeInt(255 );
     out.writeInt( -1 );

What will the example program write on the monitor?