w3resource

Java Program: File reading method with exception handling


File Not Found Exception

Write a Java program to create a method that reads a file and throws an exception if the file is not found.

Sample Solution:

Java Code:

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

public class File_Read {
  public static void main(String[] args) {
    try {
      readFile("test1.txt");
    } catch (FileNotFoundException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }

  public static void readFile(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    Scanner scanner = new Scanner(file);

    // Read and process the contents of the file
    while (scanner.hasNextLine()) {
      String line = scanner.nextLine();
      System.out.println(line);
    }

    scanner.close();
  }
}

Sample Output:

Error: test1.txt (The system cannot find the file specified)

Explanation:

In the above exercise,

  • In this program, we have a method called readFile that takes a fileName parameter. To read the contents of the file, it creates a Scanner object using the File class.
  • In the main method, we call the readFile method and provide the name of the file we want to read. If the file is not found, a FileNotFoundException is thrown.
  • In the readFile method, we declare a File object and initialize it with the given fileName. We then create a Scanner object using the file. If the file is not found, a FileNotFoundException is thrown.
  • A try-catch block is used in the main method to catch the FileNotFoundException and print an error message.

Flowchart:

Flowchart: Java Exception  Exercises - File reading method with exception handling,

For more Practice: Solve these Related Problems:

  • Write a Java program to attempt to read a file from a given path and throw a FileNotFoundException if it does not exist, then handle it gracefully.
  • Write a Java program to throw a custom ConfigurationFileNotFoundException when a required configuration file is missing.
  • Write a Java program to check the file extension of an input file and throw an exception if it is not ".txt".
  • Write a Java program to open a file for reading and throw an exception if the file cannot be accessed due to insufficient permissions.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Method to check and handle odd numbers.
Next: File reading and exception handling for positive numbers

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.