tags:

views:

202

answers:

4

Can any body help me in knowing how to pass a parameter from a Java program to a Batch file which is also used in the same java program.

The following stub indicates the piece of code where I run the batch file

Runtime rt = Runtime.getRuntime();
rt.exec("C:/test.bat");

I need to know if I could pass some parameters to test.bat which is used in the above snippet.

A: 

Why can't you insert the parameters into the exec() call?

 rt.exec("C:/test.bat <param 1>...");

I think the syntax to get at the parameters in the bat file is:

%1 for first param    
%2 for second...
Tim
+1  A: 

you can use a string array as the arg to Runtime.getRuntime().exec(). see the JavaDoc

 public Process exec(String[] cmdarray) throws IOException
akf
Wrong answer. envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.
ammoQ
You linked the right overload, but wrote the wrong one. envp is a array of environment variables, not an array of parameters. The right one is exec(String[] cmdarray) (just a single String[]), as given by ammoQ.
Matthew Flaschen
you are right. the link was the original, but i too quick to copy the signature out of source! sorry @Harish, if i led you astray. it has been corrected.
akf
+1  A: 

I am pretty sure you just stick it on the end the string, same as if you were to run it on a command line:

rt.exec("C:/test.bat "+someparm+" "+anotherparm);
larson4
+2  A: 

This should work:

String[] cmd = { "C:/test.bat", "param1", "param2" }
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
ammoQ