0

Hi I found many threads regarding how to run a dos batch from a java app and ended up getting it working. However I was stuck on the following: Using that code the process never exits, and the app is stuck.

p = Runtime.getRuntime().exec("ant.bat release",null,new File(".");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
  line = reader.readLine();
  System.out.println("execTest: " + line);
}

now if I do the reading before p.waitFor(), it works. could someone explain this to me?

working code:

p = Runtime.getRuntime().exec("ant.bat release",null,new File(".");
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
  line = reader.readLine();
  System.out.println("execTest: " + line);
}
p.waitFor();
Mark
  • 3,609
  • 1
  • 22
  • 33
Franck
  • 512
  • 1
  • 9
  • 16

2 Answers2

2

Because batch files are not executables. You need to execute cmd.exe (or, as you've tagged your question DOS, command.com) supplying the /C and the batch file as arguments.

Edit: I shouldn't be surprised that this has been asked and answered, so head over there for details. Making this answer CW.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • no no I did use cmd or cmd /C with the exact same result. Also this is not a duplicate. I am asking why one is working and the other one does not. – Franck Sep 26 '13 at 18:08
0

because the waitfor method will block until the cmd real finish and return,if when the cmd runing ,and the cmd output something to std stream or errorstream(in u view,it is inputstream),and u do not read the info from stream buffer cause the buffer full,and if the cmd still need to write,it while block until u read the data from stream buffer to provide space for cmd write.

so in u code,if the cmd do not output anything,u can get the result even if u do not read inputstream,and if the cmd output error stream,u never get the result becaue u do not read the error stream.

my best practice is read the std stream and error stream by extra two threads separately before call waitfor method.

my cmd means any command can run by Runtime