1

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

2
  • What is a? What is arr? What are the contents of your batch file? Is it possible that your batch file is so simple that it runs very fast and you miss it? Commented Sep 8, 2014 at 18:19
  • a is the argument i am passing Commented Sep 9, 2014 at 4:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.