How do I run a batch file from my Java Application?

Amara picture Amara · Mar 5, 2009 · Viewed 288.2k times · Source

In my Java application, I want to run a batch file that calls "scons -Q implicit-deps-changed build\file_load_type export\file_load_type"

It seems that I can't even get my batch file to execute. I'm out of ideas.

This is what I have in Java:

Runtime.
   getRuntime().
   exec("build.bat", null, new File("."));

Previously, I had a Python Sconscript file that I wanted to run but since that didn't work I decided I would call the script via a batch file but that method has not been successful as of yet.

Answer

Paulo Guedes picture Paulo Guedes · Mar 5, 2009

Batch files are not an executable. They need an application to run them (i.e. cmd).

On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. CreateProcess does not know anything about that.

Runtime.
   getRuntime().
   exec("cmd /c start \"\" build.bat");

Note: With the start \"\" command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.