I have a Console-Java game. The score from the game will be saved in a JSON file if Ctrl+C
is pressed. The process to save the score in a JSON file works. But I don't know, how to detect Ctrl+C
from the console and if this happens, I will save the score (just a method call).
With KeyListener it doesn't work on the console (only with JFrame as far as I know).
I couldn't find a solution to my problem on the internet.
Do I have to do it with Runtime? I have tried it, but it didn't work...
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
Test.mainThread.interrupt();
}
});
There are similar questions on Stackoverflow, but not for use on the console Catching Ctrl+C in Java
Adding a shutdown hook is the right way to do it, but
Test.mainThread.interrupt();
probably will not work. The JVM is already shutting down. Your mainThread is unlikely to have time to respond to an interrupt; once all shutdown hooks finish, Java terminates.Just have your shutdown hook explicitly perform whatever actions you need taken: