Running a method when closing the program?

后端 未结 6 1238
無奈伤痛
無奈伤痛 2020-12-03 14:22

I need to execute a method, (a method which creates a file), when I exit my program, how would I do this?

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 15:02

    Add shutdown hook. See this javadoc.

    Example:

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                System.out.println("In shutdown hook");
            }
        }, "Shutdown-thread"));
    }
    

提交回复
热议问题