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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.