Take the 2-minute tour ×

I just wanted to run a batch file using java code in win7. I can run .exe files with the code but u know it doesn't work with a batch. Where is the problem? You know even cmd.exe doesn't start with that command. But I can run other exe files, I've tried some. The code is this (with try and catch is that): none of them worked!

Runtime.getRuntime().exec("cmd.exe /c demo.bat");

i tried to do work with process and i wrote the code below. it retuened

       java.lang.IllegalThreadStateException:process has not exited
        at java.lang.ProcessImpl.exitValue(Native Method)
        at Test.Asli.main(Asli.java:38)

this is the code:

                Runtime rt = Runtime.getRuntime();
                Process proc= rt.exec("C:\\Windows\\System32\\cmd.exe"); 
                int b = proc.exitValue();
              //  int exitVal = proc.exitValue();
                //System.out.println("Process exitValue: " + exitVal);}
              catch (Exception e) {
                // TODO: handle exception
share|improve this question
Is that really your code? It can't compile. –  Mat Oct 23 '11 at 11:17
I'm sure this is not the exact code (it has 3 "'s). How does this fail? An error message, an exception, ....? Do you do anything with the Process returned by exec? –  Arnout Engelen Oct 23 '11 at 11:19
Yes, where is the problem? What do you get? an exception? What stack trace? –  JB Nizet Oct 23 '11 at 11:20
1) Be sure to read & implement the recommendations of When Runtime.exec() won't. 2) Unless the code needs to run in 1.4 or earlier, get the Process using a ProcessBuilder. –  Andrew Thompson Oct 23 '11 at 11:37
add comment

3 Answers

Try the following:

String[] cmd = {"cmd.exe", "/c", "demo.bat");

I always prefer splitting the command and the parameters myself. Otherwise it is done by splitting on space which might not be what you want.

share|improve this answer
even this doesn't make any change. no error no exception no alarm and no action! it debugs and ends. nothing happens –  Saber Solari Oct 24 '11 at 12:16
add comment

Try this:

Runtime.getRuntime().exec("cmd.exe /c start demo.bat");
share|improve this answer
add comment

Use this:

 try {
 Process p = Runtime.getRuntime().exec("C:PATH/TO/FILE/yourbatchfile.bat");
 } catch(Exception e) {

It even hides the annoying prompt window (if you want that)

share|improve this answer
add comment

Your Answer


