Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to run .bat file in JAVA

Status
Not open for further replies.

srikandula

Programmer
Dec 28, 2000
31
US
I have created a program to run the batch file.The problem is when the batch file has commands like "dir" etc its working fine.But when i have command like "cd.." its not running properly.

Say I use
c:\jdk1.3\bin\javaexamples\java batchRunner.class
where batchRunner.class is a class to run the batch file and the batch file i am calling has "cd..".By the end of the program the control should be at "....\bin\" directory as per my requirement.But while the program runs, it is going to ..\bin\ directory and as soon the as the program is complete the prompt is at "..\javaexamples\" ie no change of "cd.." is visible.

The code i am using to call the batch file is

Runtime.getRuntime().exec("mybatch.bat");


Note:-There are no compile or runtime errors , but the control is not moving one level up.If i individually run the batch file its is working well and fine.ie moving one level up.



Can any one help me in this problem.

Thanks in advance.
 
My guess is that Java will execute a Runtime.exec() call in its own sandbox, and thus only the thread started in the Runtime environment will change directories, while the Java execution thread will remain in the directory that it was started in.

I did a quick search on java.sun.com, and came up with the following:

// begin quote

changing directory in Runtime exec

The only way I got it to work is a kind of work-around like this:

Create at new .cmd file eg. cdRun.cmd with like:
<pre>
@cd %1
%2 %3 %4 %5 %6 %7 %8 %9 %10
</pre>

Then invoke like Runtime.exec(&quot;cmd.exe /c cdRun.cmd &quot; + yourStartDir + whatEverYouWantToStart);

// end quote

I don't know if this will work, but maybe it's worth a shot...

Best,
Adam Rice
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top