1

i am using the following in one of my application.

public static void concatenation(List<String> commands) throws IOException {
    if (commands.get(1).equals(">")) {
        String path = history.getFilePath();
        File file = new File(path + "\\" + commands.get(2));
        if (file.exists() && file.isFile()) {
            try (FileWriter writer = new FileWriter(file)) {
                Scanner scanner = new Scanner(System.in);
                String line;
                System.out.println("Write to file. Press Ctrl+C to stop.");
                while (true) {
                    try {
                        line = scanner.nextLine();
                        writer.write(line + System.lineSeparator());
                        writer.flush();
                    } catch (Exception e) {
                        System.out.println("Interrupted. Stopping...");
                        break;
                    }
                }
                scanner.close();
            } catch (IOException e) {
                System.out.println("Error writing to file: " + e.getMessage());
            }
        }
    } else {
        System.out.println("bash : " + commands.get(1) + " : unrecognized operator");
    }
}

i want to exit out of the while loop when ctrl + c is pressed. And it is a console application. How to achieve this?

  • Does this answer your question? [How can I "intercept" Ctrl+C in a CLI application?](https://stackoverflow.com/questions/1216172/how-can-i-intercept-ctrlc-in-a-cli-application) – experiment unit 1998X Feb 03 '23 at 09:11
  • 1
    Unrelated note, don't close any reader wrapping around `System.in`, unless you are sure it's the last statement in your program (in which case there is no point in doing it), you won't be able to read again. Move the scanner outside from the `try-with-resources` block as well - it will close it. – Chaosfire Feb 03 '23 at 09:16

0 Answers0