2008年11月26日 星期三

How to run a batch file from Java

How to run a batch file from Java, it seems not a very hard problem.

We can find a lot of information from Google. But I still waste two hours to complete this task.
The reason to run the a batch file in Java code is because I want to show up a GattProject user interface when some conditions occured.

Everybody will tell you just using Runtime.getRuntime.exec("YourBatchFileCommand"); then this job is done.
But I tried several times it never works for me.
Finally, I found one tricky thing that we need to put the "cmd /C Start " command before batch file.


Runtime load = Runtime.getRuntime();
Process p = null;
String[] command ={ "cmd", "/C Start D:/projects/GanttProjectTest/ganttproject.bat HouseBuildingSample.gan" };
try {
p = load.exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

However, this still can't open the GanttProject successfully due to some environment issues such as ClassPath setting.
The solution is copy all the files under GanttProject under your Java Program root folder. In my case the Java class is under "D:/projects/GanttProjectTest/bin".

沒有留言: