1

I need to start a batch using java and after a few seconds i need to stop the running batch file.

here is my code

try {
        Process process=Runtime.getRuntime().exec("cmd /c start  D:/test.bat");
        Thread.sleep(20*1000);
        process.destroy();
    } catch (Exception e) {
        e.printStackTrace();
    }

my code failed to stop the batch file.

Lalchand
  • 7,627
  • 26
  • 67
  • 79

3 Answers3

2

It isn't that simple since you have to kill an independent operating system process you have just started. Looks like How to find and kill running Win-Processes from within Java? might help you.

In short: you have to find the PID of a batch script (actually, of a cmd process running your batch script) and kill it using taskkill.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

If the batch is running in cmd.exe using Java, run this

Process prClose = Runtime.getRuntime().exec("taskkill /im cmd.exe");
0

If you run a java or javaw on your .bat file, you need to terminate your batch file first:

Runtime.getRuntime().exec("taskkill /f /im jqs.exe") ;
Runtime.getRuntime().exec("taskkill /f /im javaw.exe") ;
Runtime.getRuntime().exec("taskkill /f /im java.exe") ;

And stop cmd(if needed)

Runtime.getRuntime().exec("taskkill /f /im cmd.exe") ;

Hope this help!

Huy Hóm Hỉnh
  • 597
  • 7
  • 18