我正在开发一个简单的控制台应用程序,但遇到以下问题:当用户关闭应用程序时,我必须拦截并执行操作(例如在 shell 中单击 CTRL+C) .
据我了解,我可以在运行时使用 addShutdownHook() 方法(但我绝对不确定这个断言),但它对我不起作用。
我做了这样的事情:
public class MainApp {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("STOPPED !!!");
}
});
...................................................................
...................................................................
MY APPLICATION BEHAVIOR
...................................................................
...................................................................
}
}
通过这种方式,我期望应用程序必须启动,然后当用户通过 CTRL+C 退出应用程序时,它会进入定义的 run() 方法进入new Thread()
发生的情况是,如果我按 CTRL+C 终止应用程序,应用程序将退出,但不会执行 run() 方法,因此不会处理应用程序结束
出了什么问题?我缺少什么?当用户退出我的控制台应用程序时如何正确拦截?
最佳答案
我尝试了下面的代码,当按 Ctrl+C 时它对我有用。请注意,应在用户按 Ctrl+C 之前调用 addShutDownHook() 方法,如 docs 中所述。 :
Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook. Attempting either of these operations will cause an IllegalStateException to be thrown.
public class MainApp {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
String text = "kkkk";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
System.out.println("STOPPED !!!");
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("the entered int: " + i); // will print the variable
System.out.println("my app behaviour");
}
}
当应用程序启动并按 Ctrl+C 时,将在当前目录中写入一个文件,我可以看到以下输出:
Pedros-MacBook-Pro:stackoverflow pedro$ java -jar target/stackoverflow-1.0-jar-with-dependencies.jar ^CSTOPPED !!!
关于java - 当用户退出Java控制台应用程序时如何正确拦截和处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43916126/