Triple777er
Triple777er

Reputation: 631

Java interactive input EOF

I'm trying to implement a user input interface for a board game. I'm trying to get user input one at a time and then writing it to a file (since I need to save the list of moves made by the user). What I have so far, works well (reading input and writing it to file), however, whenever the user wants to stop inputting, the program just stops working. I.E; when you press ctrl+c, the program just ends.

Here is what I have so far, the fileName variable has been declared outside the main function

public static void main(String[] args) throws IOException {
    BufferedReader inputReader = new BufferedReader (new InputStreamReader (System.in));
    try {
        FileWriter outFile = new FileWriter (fileName);
        PrintWriter out = new PrintWriter (outFile);
        System.out.print ("Enter move: ");
        String line = inputReader.readLine();
        while (line != null) {
            System.out.print ("Enter move: ");
            out.write(inputReader.readLine());
            out.write(" ");
            }
            out.close();
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }

    System.out.println ("Reached here");
}

What I'm trying to do is whenever the user wants to stop inputting, I want to get to the print line where it says "Reached here". I want to do this because once outside of the loop, I can read the file and then split the input and maniplate it. I remember whilst programming in C, there used to be while (input != EOF); where whenever the user entered ctrl+d or ctrl+c, it stops whatever it is doing and then moves onto the next line of code. How can I do this in java?

Many thanks.

Upvotes: 0

Views: 3503

Answers (3)

Dimitar
Dimitar

Reputation: 2402

You can catch the Ctrl+C signal using a SignalHandler. Although I wouldn't recommend this as it would make it difficult for the user to exit your application. Instead you could stop input when the user enters nothing, or use a different command signal.

Upvotes: 1

You need to agree with a command indicating that user is done (for example "EOF") and add the following in your while loop:

    while (line != null) {
        System.out.print ("Enter move: ");
        String r = inputReader.readLine();
        if ( r != null ) {
           if ( "EOF".equals(r) ) break;
        }
        out.write();
        out.write(" ");
    }

Upvotes: 0

MeBigFatGuy
MeBigFatGuy

Reputation: 28568

If you flush after each write, you should at least get a complete file when the user hits control-c.

As for processing more information after control-c happens, you can do that by using a shutdown hook such as:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { 
        // do something before quiting
    }
});

however, i don't know that you can cancel the termination.

I would choose a more normal character input for the 'no more input' action.

Upvotes: 2

Related Questions