Detect EOF in Java

Waleed Mar 29, 2022 Jan 19, 2022
Detect EOF in Java

In this tutorial, we’ll introduce how to detect EOF (End OF File) using a while loop in Java. We’ll also discuss developing a program that continues reading content until the end of the file is reached.

From the programming standpoint, the EOF is a specialized type that developers use to continually read input, whether from the file or keyboard console. This process continues until there is no more data to retrieve.

It is worth mentioning here that data in a file can be modified or altered at any moment. So, it is practically impossible to apply a sentinel controlled loop over that file. 

For this reason, we strongly recommend you always use an end-of-file loop to mitigate the potential threat of the problem mentioned above.

We use the keyboard as an input source in the below code example.

package sampleProject;
import java.util.*;
import java.util.Scanner;
public class Codesample {
   static Scanner console = new Scanner(System.in);
   public static void main(String []args) {
	 int total_ages = 0;
         int age;
         while(console.hasNext()) {
            age = console.nextInt();
            total_ages = total_ages + age;
             }

	 System.out.println("Total ages are:" + total\_ages);
      }
}

Output:

99
90
88
Ko
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at sampleProject/sampleProject.Codesample.main(Codesample.java:15)

We begin by declaring and initializing the object of the scanner class that. After that, I have declared some other variables to use in our code.

You might have noticed that we use console.hasNext() as the loop iterating condition. We already know that console is the object of our input class scanner.

On the other hand, hasNext() is a pre-defined method in the input class Scanner. This expression only returns true if there is an integer input. Otherwise, it returns false.

Compile this code on your own and see the output. It is pretty evident from the output that our program continues reading the data until we provide the wrong input type. In that case, this program throws an Input mismatch exception. 

File as an Input Source

In another example, we use an end-of-file controlled while loop to read data from the file continually. 

Let’s say we want to read all the data from the file Students\_Result.txt. The file contains students names followed by their test scores.

Our goal in this program is to output a file that displays students’ names, test scores, and grades. 

package sampleProject;
import java.util.*;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Codesample {
     static Scanner console = new Scanner(System.in);
     public static void main(String []args) throws FileNotFoundException {
         // declare file name as an input object
           Scanner inputFile = **new** Scanner(**new** FileReader("Students\_Result.txt"));
         // declare the output object that stores data we want to display
            PrintWriter outputFile = **new** PrintWriter("Students\_Record.txt");
         // Declare variable to store first name and last name
            String firstName, lastName;
         // declare variable to store score
            double score;
         // declare variable to store student's grad
            char grade = ' ';
         // declare and initialize counter variable
            int counter = 0;
         // continue reading data from the file until the loop reaches end of file
            while (inputFile.hasNext()) {
               // read first name from the provided file
                  firstName = inputFile.next();
               // read last name from the file
                  lastName = inputFile.next();
              // read score of the students from the filee
                 score = inputFile.nextDouble();
              // increment counter variable
                 counter++;
              // To evaluate grade of the students, we are using the switch statemet
		 switch ((int) score / 10 ) {
                   case 0:
                   case 1:
                   case 2:
                   case 3:
                   case 4:
                   case 5:
                      grade = 'F';
                      break;
                   case 6:
                       grade = 'D';
                       break;
                   case 7:
                      grade = 'C';
                      break;
                   case 8:
                      grade = 'B';
                      break;
                   case 9:
                   case 10:
                      grade = 'A';
                      break;
                      default:
  	   outputFile.println("Your score does not meet our criteria");
           
      }
     //   Display retrieved data using the outputFile object we have declared earlier
          outputFile.println(firstName + " " + lastName + " " + score + " " + grade);

           }
     // If no data is found in the output file 
        if(counter == 0) 
          outputFile.println("There is not data in your input file");
    // close output file upon reading all the data from it.
       outputFile.close();
  }

}

Output:

Waleed Ahmed 89.5 B
Bob Alice 90.0 A
Khan Arshad 100.0 A
Waqas Jameed 65.5 D
Danish Taimoor 70.5 C
Muaz Junaid 80.5 B
John Harris 88.0 B

Compile and run this program on your system to see what happens.