Q:

Java program to read Boolean value from the file

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

nerdutella
 

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now