I want to execute a batch file from a java program.
I am using the following command.
Runtime.getRuntime().exec("server.bat");
But the problem is I want to give a reative path instead of absolute path so that I can deploy that java project on any comp.
The dir structure of the project is like as follows:
com
|
project
|
------ parser
| |_____ Main.java
|
-------util
|_____ Server.bat
I want to run the "Server.bat" file in the "util" dir from the "Main.java" file in the "parser" dir.
You can use
ProcessBuilder
for this. It provides much more control thanexec
. Particularly, it allows to set working directory with methoddirectory
.Example:
Of course, your app must get deployDir from somewhere. It can be set in environment, in application configuration file, it can be current user directory or anything else.
When Java is running and you use Runtime.exec() with a relative path, relative means relative to the current user direcory, where the JVM was invoked.
This may work
if you start java from com's parent directory.
Or you must calculate an absolut path:
I forget, read When Runtime.exec() won't.
The second parameter to exec is a String[] of args for the environment settings (null means inherit the process' current ones) and the third parameter to exec should be a file providing the working directory. Try this:
You have to run "cmd.exe" with the arguments "/c" and "server.bat":
You're best bet is to store the installation directory of the application on the system and then use that to build your paths within the application. System.getProperty("user.dir") should work on Windows and Unix platforms to get the current working directory, but it is system dependent so be aware of that.
Plexus utils provides a Commandline type that can invoke an arbitrary command line and handle parsing of the output.