2

How do I execute a .bat or .exe within my java program that is in a sub-folder within the main folder that holds my java program.

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

The code above works perfectly fine when the .bat is in the same folder as the java program. But if my program's .java and .class files were organized in a package (and the .bat would be in a separate folder), how would I call that bat program?

Arc
  • 441
  • 1
  • 9
  • 26
  • Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Feb 08 '14 at 02:40

3 Answers3

1

If the .bat file is in a different folder you should pass its full absolute path to cmd.exe. Also, to get the correct quoting you should use the method that takes an array as argument:

String[] cmd = {"cmd", "/c", "start", path};
Runtime.getRuntime().exec(cmd);

If you know the location of the .bat file relative to your .jar file, you can find it using the properties of the Class object. See for example How to get the path of a running JAR file?

Community
  • 1
  • 1
Joni
  • 108,737
  • 14
  • 143
  • 193
0

May not be feasible in your case, but what if you added the location of the batch file to your execution path?

Trenin
  • 2,041
  • 1
  • 14
  • 20
0

You can use the full absolute path to example.bat or the relative path from your Working directory.

Guy Bouallet
  • 2,099
  • 11
  • 16