简体   繁体   中英

How to stop an input-waiting Windows batch process in Java?

I have a Windows batch file simple.bat which produces some output in stdin, and ends with a pause . I want to run this batch file and then process the output in my Java code.

// create a Java process with simple.bat
Process p = Runtime.getRuntime().exec("cmd /c simple.bat");

// get the output from the process p
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    builder.append(line);
    builder.append(System.getProperty("line.separator"));
}

String result = builder.toString();

The problem with the above code is that simple.bat ends with a pause and that makes p still hanging in there waiting for the key to be pressed. As a result, eventually reader.readLine() will be blocked and never returns.

Unfortunately, simple.bat is passed on to me as-is. I cannot remove the pause line.

I can add

Thread.sleep(1000);
p.destroy();

after the exec("cmd /c start simple.bat") line to terminate the process p before processing its output. What if the batch file is run on slow machine? I am seeking advice is there a better way then asynchronously stopping the process. Thank you very much!!

If your script doesn't require any input sent to it, and you are running it as cmd /c simple.bat , then the simplest thing to do is to close the process's standard input:

p.getOutputStream().close();

I ran a quick test myself, and this dismissed the pause and let the script terminate. You will of course have the extra line Press any key to continue . . . Press any key to continue . . . in your output, but I imagine you can deal with that.

Destroying the process can be correct as a fallback. You will have to think about how you would prefer your application to fail: is aborting to soon worse than a hanging process? Which of the failures will the user actually notice?

In most cases both of the above are undesirable.

If you know you have reached the pause (based on the last readline() ), you can actually write to the process. This can be done by getting an output stream Process.getOutputStream() . I haven't been able to test this, but normally pause should also react to characters written this stream.

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