views:

864

answers:

3

When I execute the batch file directly in DOS, everything runs as expected. But when I execute the batch file from Java runTime, it will run only the commands that invoke jar files (ie. invoke the JVM). It does not run any native dos commands.

One problem is that I have no console to know why this is happening. I'm wondering if it's a permissions problem, but I have no idea. Anyone out there see this before?

The Java code used looks something like this:

Runtime.getRuntime().exec("c:\targetFolder\myBatch.bat"); // (Edited here for simplicity.)


The batch file looks something like this (noting that I've simplified it):
myBatch.bat:

call java myJar.jar blah blah --- yes
copy outputFile.out outputFile.bak --- NO
mkdir testDir --- NO
call java myJar.jar blah blah --- yes
call someOther.bat --- NO

The ---yes lines run fine and I see the expected results
The ---no lines do not run, but I have no idea why not b/c there is no console to tell me.

Thanks for any help!! Mike

A: 

The fact that the second java calls executes indicates that all your NO lines are still executing, but just not displaying any output. Have you tried turning on echo on via

@ECHO ON

in your first line?

Secondly, your problem is probably the wrong working directory. Specify the working directory like so

Runtime.getRuntime().exec("c:\targetFolder\myBatch.bat",null,"c:\targetFolder");
enderminh
+4  A: 

You have to run the Windows command processor (the shell), giving it the batch file as an argument.

Runtime.getRuntime().exec( "cmd.exe /C c:\\targetFolder\\myBatch.bat" );
Jonathan Feinberg
You beat me by a few seconds with that answer
martinatime
Thanks for the response race! :)Unfortunately, it doesn't solve my initial problem (though I appreciate improving my method of calling the batch).After playing with it I found that I *could* call native DOS commands, but only if they did not read/write from a particular folder. I believe the folder is somehow being locked by the JVM during a previous call in which I create a File object on that folder to view its contents. Trouble with that is I have no way to "unlock" it, and File class has no 'close' method. Is there a quick fix for this? Thanks again!
Instead of using Runtime.exec(), you should be using ProcessBuilder, and retrieving stand error from it, to SEE what's going wrong. See http://www.rgagnon.com/javadetails/java-0014.html for example.
Jonathan Feinberg
I'll head that way; much obliged!
A: 

What's the current working directory when you run the shell script? Could it be, that the files are not found in the working directory of the running JVM (which is inherited by the cmd process)? In other words: could it be the case, that the batch script tries to execute the commands, but does so in the wrong directory?

Dirk