Java program to read Boolean value from the file

In this java program, we are going to read Boolean value from the file using hasNextBoolean() method of Scanner class.

Given a file and we have to read a Boolean value from the file.

What is Boolean value?

The word Boolean (which is a data type and class both in Java) can be represent by either True or False.

Here, we are creating an object scan of Scanner class by passing object of "File" class, which is initializing with the file name.

The method hasNextLine() is using to check whether data is available in the file or not, if method returns "True" then we are reading byte using scan.nextBoolean() and printing on the console.

Consider the program:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadBoolean {
  public static void main(String[] args) throws FileNotFoundException {
    // here file is the object of the File Boolean.txt
    File file = new File("E:/Boolean.txt");

    // scan is the object of scanner class. //
    Scanner scan = new Scanner(file);

    // this loop will read the given file line by line
    while (scan.hasNextLine()) {
      // this loop will check will the file contain boolean value
      if (scan.hasNextBoolean()) {
        // in this loop if the boolean is found then it return it
        if (scan.nextBoolean()) {
          // this will print the boolean value
          System.out.println(scan.nextLine());
        } else {
          break;
        }
      } else {
        // will continue searching till the file ends
        System.out.println(scan.nextLine());
      }
    }
    scan.close();
    // close the above file.
  }
}

Output

IncludeHelp

Note: File "Boolean.txt" contains "IncludeHelp".




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.