In computer programming, checking for end of file (EOF) is a crucial task for reading data from a file. In Java, there are several ways to check for EOF, the most common of which is to use the hasNext() method of the Scanner class. The hasNext() method returns a boolean value indicating whether there is another token in the input. If the hasNext() method returns false, it means that the end of the file has been reached. Here is an example of how to use the hasNext() method to check for EOF:
Scanner scanner = new Scanner(new File("myfile.txt")); while (scanner.hasNext()) { String line = scanner.nextLine(); // Do something with the line } scanner.close();
Another way to check for EOF in Java is to use the read() method of the InputStream class. The read() method returns an integer value representing the next byte of data in the input stream. If the read() method returns -1, it means that the end of the file has been reached. Here is an example of how to use the read() method to check for EOF: