-1

I'm trying to run a.bat file which is located here:

C:\A\B\C\D E\F

So I invoke:

cmd /c "cd C:\A\B\C\D E\F && a.bat"

on the CMD and I can see the execution of the file.

Now I want to run this file from Java and then delete it, so I run:

Runtime.getRuntime().exec("cmd start /wait /c "+ "\"cd C:\\A\\B\\C\\D E\\F && a.bat\"");

(the /wait because I want to delete the file only after its execution)

but I don't see the execution of the program (the CMD doesn't open). How can I fix this?

Maroun
  • 94,125
  • 30
  • 188
  • 241

4 Answers4

1
Runtime run = Runtime.getRuntime();  
        Process process = null;  
        String cmd = "cmd start /wait /c "+ "\"cd C:\\A\\B\\C\\D E\\F && a.bat\"";  
        try {  
            process = run.exec(cmd);
            process.waitFor();
            System.out.println(process.exitValue());
        }  
        catch (IOException e) {  
            e.printStackTrace();  
            process.destroy();  
        } 
1218985
  • 7,531
  • 2
  • 25
  • 31
1

What I suggest you to put the command :

start /wait /c "cd C:\A\B\C\D E\F && a.bat"

in a seperate batch file (say abc.bat).
And then run that abc.bat file using following line:

Process process = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "abc.bat");
process.waitFor();//throws InterruptedException . So it must be caught.
if (process.exitValue() == 0 )
{
 System.out.println("Process is executed successfully!");
}
Vishal K
  • 12,976
  • 2
  • 27
  • 38
1

That is a bit of a mess. Sure, your first command works from the command prompt, but then you attempt to run an entirely different (and disfunctional) command from within java.

I'm assuming you are going to delete a.bat from within java, in which case the START /WAIT will never do you any good any way. The child process will wait for the target of START to finish, but that has no impact on your java process.

Why not let the child process delete the file? I believe the following will work.

Runtime.getRuntime().exec("cmd /c \"cd C:\\A\\B\\C\\D E\\F&&a.bat&&del a.bat\"");

The delete command will not fire until after the batch script has completed. If you want to always delete the script, even if it fails, then change && into &.

dbenham
  • 127,446
  • 28
  • 251
  • 390
0

I found a solution :)

I Moved start /wait to the second part of the command and it worked:

Runtime.getRuntime().exec("cmd "+ "\"cd C:\\A\\B\\C\\D E\\F && start /wait a.bat\"");

Maroun
  • 94,125
  • 30
  • 188
  • 241