0

I'm reading stdin using a scanner. The scanner stops reading if I send ^D (end of tranmission char) via command line.

Now let's say that I want the scanner to stop if the last line read is "exit".

I'm trying to send this ^D signal to stdin but the scanner does not stop reading.

My attempt so far, this is the read loop:

    while (scanner.hasNextLine())
    {
        try
        {
            String nextLine = scanner.nextLine();
            action.accept(nextLine);
        }
        catch (Throwable th)
        {
            onError.accept(th);
        }
    }

and action:

        if (line.equals("exit"))
        {
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out))) 
            {
                writer.write("\u0004");
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println(line);
        }
Jorge Lavín
  • 937
  • 8
  • 22
  • You could just set the scanner to null `scanner = null;` or just break the loop? Or if you really want this will work `if (line.equals("exit")) {scanner.close();}` but warning, you should not close scanner, it will also close system.in https://stackoverflow.com/questions/26245468/what-does-scanner-close-do – sorifiend Feb 11 '21 at 20:51
  • In the above code, you send "\u0004" to standard output not to stdin. – lkatiforis Feb 11 '21 at 20:56
  • 2
    **On UNIX TERMINAL** input (i.e. using the 'tty' driver or discipline), ^D aka EOT aka \004 normally causes end-of-file. In other places it does not do this. What you want to do is either return a status that tells the main loop to exit, or throw an exception that _causes_ the main loop to be terminated. – dave_thompson_085 Feb 12 '21 at 04:06

0 Answers0