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;

public class ReadFile {
    public static void main(String[] args) throws IOException {
        //Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(;
        // 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);


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

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