views:

407

answers:

3

I'm trying to run two bat files from a Java app. I'm using:

try
{
  Runtime rt = Runtime.getRuntime();
  Process proc = rt.exec(fullCommand);
  InputStream stderr = proc.getErrorStream();
  InputStreamReader isr = new InputStreamReader(stderr);
  BufferedReader br = new BufferedReader(isr);

  int exitVal = proc.waitFor();
  System.out.println("Process exitValue: " + exitVal);

  System.out.println("Working...");
} //End try

catch (Throwable t)
{
  t.printStackTrace();
} //End catch

} //End method

The bat file calls another bat file. It never seems to exit and return control to the original bat file.

From 1.bat

set zzname=%1
zzlookup.bat %zzname%

The other bat file runs a few commands and then should exit. Do I need to do something special with the runtime part?

Thanks in advance, Dustin

+3  A: 

To call one batch file from another and still get back to the original, you need

call zzlookup.bat %zzname%

Otherwise as soon as zzlookup.bat exits, the process will stop.

For example:

withcall.bat:

@echo Before
@call other.bat
@echo After

direct.bat:

@echo Before
@other.bat
@echo After

other.bat:

@echo Other

Output:

c:\Users\Jon\Test>withcall
Before
Other
After

c:\Users\Jon\Test>direct
Before
Other
Jon Skeet
I'm just curious why DOS/Windows would think you *didn't* want to return to the original batch file
matt b
No idea - my guess is it's just a mistake from a *long* time ago which now can't be fixed for compatibility reasons.
Jon Skeet
I've added the call and it still isn't working. I can make the call from just the command line (not going through Java) and it executes fine. Do I need another stream reader for the other process or something even though Java isn't executing it?
Dustin
You shouldn't need another `StreamReader`, but I don't see you actually reading from the output - if it runs out of internal buffer, that could explain it. Try reading from the reader in a different thread. Does it normally create a lot of output?
Jon Skeet
+1  A: 

If the batch file generates output, you need to drain the streams representing standard and error output.

There are already working examples here.

javashlook
+3  A: 

In addition to the advice above I don't think Runtime.exec allows running .bat files directly. Try prefixing your command with "cmd \c" first.

See http://ant.apache.org/manual/CoreTasks/exec.html

Actually, it's "cmd /c" but otherwise, good catch.
rob