Skip to content

How to close program if text document is not found

This is the top of my program. You are to type in a .txt file name for it to open.

Problem: How do I have the program display an error message and close the program if .txt file is not found?

import java.util.Scanner;
import java.io.*;

public class ReadFile {
    public static void main(String[] args) throws IOException {
        //Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);
        // Get the filename.
        System.out.print("Enter student name: ");
        String filename = keyboard.nextLine();
        // Open the file.
        //Runtime error is the file isn't found
        File file = new File(filename + ".txt");
        Scanner inputFile = new Scanner(file);

Answer

You can put File in try catch block like this and show a relevant message:

try{
    File file = new File(filename + ".txt");
}
catch(FileNotFoundException e)
{
    System.out.print("exception occur exception message= " +e.getMessage());
}