Gio
Gio

Reputation: 21

Run a .bat file on closing java app

I want to run a .bat file when I close my Java application.

I try, but when I close Java app the bat file doesn't start.

Upvotes: 2

Views: 1264

Answers (4)

JRL
JRL

Reputation: 78003

If your app is a Desktop app extending SingleFrameApplication, you can override its exit method: public void exit(EventObject event) and add the code to start your file there.

Upvotes: 0

Neeraj
Neeraj

Reputation: 303

Please go through this http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html. Use Runtime.getRuntime().addShutdownHook(thread) to associate it.

Upvotes: 0

Guillaume
Guillaume

Reputation: 14656

You might want to look into shutdown hooks. Basically you can register an unstarted thread, it will be started by the JVM when the exit process is started.

Runtime.getRuntime().addShutdownHook(thread)

According to the doc:

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

Upvotes: 4

Nick Fortescue
Nick Fortescue

Reputation: 44173

I can think of two options.

  1. Start your Java application from within one batch file or ant file, and then have this automatically run another when you finish.
  2. Intercept when your application closes using java code, then start a batch file running from Java as a subprocess. You will probably need to use windows specific methods to keep it running after you exit, if you don't want to keep your application waiting around.

Only 1 will work if your process is killed. How are you trying to do it at the moment, and how is it failing? Without this information we can't help you.

Upvotes: 1

Related Questions