简体   繁体   中英

Why running this batch file from my Java Application fail?

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();

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM