Get Batch File Output

I need to execute and capture the output of a batch file from within a java program. The batch file sets up some environment variables and then runs an exe. I can't directly run the exe, I need the batch file to set up the environment. I have a method that I use to get the output of exe's and shell commands and whatnot, but it does not seem to work in this case. Here is the method I am using to try and get the output:

String cmd ="cmd.exe /c batchfile.cmd";

Process p = Runtime.getRuntime().exec(cmd);

InputStream iStr = p.getInputStream();

InputStreamReader reader =new InputStreamReader(iStr);

BufferedReader buff =new BufferedReader(reader);

String line =null;

while ((line = buff.readLine()) !=null){

//process line

}

}

iStr.close();

reader.close();

buff.close();

Any help is appreciated, thanks.

[1202 byte] By [Losinga] at [2007-11-27 10:58:22]
# 1

Not sure whether the exe's process output is considered the batchfile's output. Why can't you just setup the environment with Java?

jGardnera at 2007-7-29 12:15:07 > top of Java-index,Java Essentials,Java Programming...
# 2

It's a lot of complicated mess and the batch file may change periodically, the java program needs to be independent of the batch file.

And you're right I think, the exe's output is the output of a different process. What I need may be impossible :(

Losinga at 2007-7-29 12:15:07 > top of Java-index,Java Essentials,Java Programming...
# 3

Not necessarily. in the batch file, when you have it execute the exe, have it redirect the output to a file or better a blocking message-oriented pipe.

: start blah.exe > pipe

you can create pipes with, for example, mkfifo on linux.

Or you might be able to use a PipedInputStream wrapper around a file that you are going to output to (from the batch file) and use receive. I think that may wait until there is new data in the file.

Or if all else fails just spinlock until the file size > 0. or while the InputStream).available() is = 0. Or try read(), that might block for you too.

jGardnera at 2007-7-29 12:15:07 > top of Java-index,Java Essentials,Java Programming...
# 4

Apparently file input streams can block like a normal input stream (where it waits for input):

http://www.java2s.com/Code/Java/File-Input-Output/DemonstratesstandardIOredirection.htm

jGardnera at 2007-7-29 12:15:07 > top of Java-index,Java Essentials,Java Programming...
# 5

Thank you very much for the information, I'll look into these suggestions.

Losinga at 2007-7-29 12:15:07 > top of Java-index,Java Essentials,Java Programming...
# 6

You also should read and understand this article about using Runtime - especially the parts about reading from external processes.

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

ChuckBinga at 2007-7-29 12:15:07 > top of Java-index,Java Essentials,Java Programming...