itin
itin

Reputation: 450

Executing Batch file from java and open the cmd of running batch file

I was trying to execute the batch file from java. My requirement is when the java execute the batch file, the command window should open. currently nothing happen.

My code is:

String[] batchArg = {"cmd", "/k", "cd /d C:\\<path to batch file> & <batchfilename>.bat",a[1],arr[2]};
Runtime.getRuntime().exec(batchArg);

also try this:

 String[] batchArg = {"cmd","C:\\<path to batch file> & <batchfilename>.bat",a[1],arr[2]};
Runtime.getRuntime().exec(batchArg);

I have tried /C as well

if i run the batch file from start menu with this command or by double click it is executing correctly.

please let me know,

thanks in advance

Upvotes: 1

Views: 3874

Answers (2)

Bryan Moore
Bryan Moore

Reputation: 49

Try adding a waitFor() to your code.

Process p = Runtime.getRuntime().exec("cmd /C e:/Users/Bryan/touchafile.bat");
p.waitFor();

Also you might find looking at the output of the process useful.

InputStream error = p.getErrorStream();
InputStream output = p.getInputStream();
System.out.println(IOUtils.toString(error));
System.out.println(IOUtils.toString(output));

Upvotes: 0

Rainbolt
Rainbolt

Reputation: 3660

Batch files alone can't be executed. They need an application to run them. In your case, that application is cmd.exe. Windows Explorer takes care of this when you run a batch by clicking on it. Java doesn't have this luxury.

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

Another similar command that anyone reading this would be familiar with is:

java HelloWorld.java

Notice how you had to specify which application you wanted to use to run this file? Typing the file name, HelloWorld.java, all by itself would not accomplish much.

*The /c switch puts the output in a new window which terminates when the batch file has completed.

Upvotes: 2

Related Questions