简体   繁体   English

如何在java中等待并关闭命令提示符

[英]how to give wait & close the command prompt in java

I am using the following code to execute a batch file: 我使用以下代码来执行批处理文件:

java.lang.Runtime rt = java.lang.Runtime.getRuntime();
Process pr = rt.exec("MyBatch.bat");

My batch file takes some time to execute. 我的批处理文件需要一些时间来执行。 I want my servlet process to wait till the batch file execution completes. 我希望我的servlet进程等到批处理文件执行完成。 I would like to close the command prompt after executing the batch file. 我想在执行批处理文件后关闭命令提示符。 How can I do this? 我怎样才能做到这一点?

Use Process.waitFor() to have your thread wait for the completion of the batch file's execution. 使用Process.waitFor()让您的线程等待批处理文件的执行完成。

java.lang.Runtime rt = java.lang.Runtime.getRuntime();
Process pr = rt.exec("MyBatch.bat");
pr.waitFor();

You may also want to look at using ProcessBuilder instead of Runtime.getRuntime().exec() if you need access to the console's output and/or input. 如果需要访问控制台的输出和/或输入,您可能还想查看使用ProcessBuilder而不是Runtime.getRuntime().exec()

The most straightforward way would be to use the .waitFor() method of the process object you created: pr.waitFor(); 最直接的方法是使用您创建的进程对象的.waitFor()方法: pr.waitFor();

This is a blocking call, meaning that no other code will be executed before this call returns. 这是一个阻塞调用,这意味着在此调用返回之前不会执行任何其他代码。

As others have said, you can use Process.waitFor(). 正如其他人所说,您可以使用Process.waitFor()。 However, before doing this you must start another thread that continually reads the contents of the process's output and error streams; 但是,在执行此操作之前,您必须启动另一个不断读取进程输出和错误流内容的线程; otherwise if there is an error that causes lots of output your application will hang. 否则,如果出现导致大量输出的错误,您的应用程序将挂起。

Alternatively you can have your batch file redirect output and errors to a file. 或者,您可以让批处理文件将输出和错误重定向到文件。

查看Process类的文档。

You can trace the InputStreamReader from your process. 您可以从进程中跟踪InputStreamReader。 and trace for the lines inside bat file. 并跟踪bat文件中的行。

When you are EOF then exit from command line 当您是EOF时,然后退出命令行

see the Example or full source code. 请参阅示例或完整源代码。 click here 点击这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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