import java.util.*;   // for the Scanner class
import java.io.*;     // for the File class (I think)

/**
    this asks the user for the name of a file to read from,
    and it tries to read the 1st line from that file
    and print it to the screen<br /><br />

    (This is using a Java-8-friendly approach, suitable
    for use on nrs-projects...)

    @version 2021-11-15
    @author Sharon Tuttle
*/

public class FileInputEx
{
    /**
        asks the user to enter a file name and tries to
        read its 1st line and print it to the screen

        @param args not used here
    */

    public static void main(String[] args)
    {
        // get file to read from from the user

        System.out.println("Please enter name o file "
                           + "to read from (relative to the "
                           + "local directory:");

        Scanner userIn = new Scanner(System.in);
        String desiredFile = userIn.nextLine();

        System.out.println("You entered: " + desiredFile);

        // THIS Scanner constructor for attaching a Scanner
        //    to a file MIGHT throw a FileNotFoundException,
        //    and it is a CHECKED exception, so this NEEEEDS
        //    to be in a try-catch block

        Scanner inFile = null;

        try
        {
            inFile = new Scanner(new File(desiredFile));
        }
        catch (FileNotFoundException exc)
        {
            System.err.println("Oh no! cannot open "
                               + desiredFile 
                               + "! Goodbye!");
            System.exit(1);
        }

        // but if I reach here, now my Scanner methods
        //     let me read from this file!

        String firstLine = inFile.nextLine();

        System.out.println("read from " + desiredFile 
                           + ": " + firstLine);

        inFile.close();
        userIn.close();
    }
}