英文:
Java find out if Batch file ran successfully
问题
我正在Java中运行一个批处理文件,方法如下:
Runtime
.getRuntime()
.exec("cmd /c " + filepath);
有没有办法从Java中判断批处理文件是成功运行还是失败的?
英文:
I'm running a Batch file from Java like so:
Runtime
.getRuntime()
.exec("cmd /c " + filepath);
Is there any way to find out if the Batch file ran successfully or failed from within Java?
答案1
得分: 2
使用 Process
实例,该实例是通过 Runtime#exec(String)
构造的:
Process p = Runtime.getRuntime().exec("cmd /c " + filepath);
您可以调用 Process#waitFor
方法,该方法会「使当前线程等待,直到由此 Process 对象表示的进程终止为止。」然后,可以通过 Process#exitValue
来查看进程是否成功完成。
您还可以通过获取其输入和输出流与进程进行交互:
InputStream inputStream = p.getInputStream(), errorStream = p.getErrorStream();
OutputStream outputStream = p.getOutputStream();
英文:
Use the Process
instance that Runtime#exec(String)
constructs:
Process p = Runtime.getRuntime().exec("cmd /c " + filepath);
You can call Process#waitFor
which "causes the current thread to wait, if necessary, until the process represented by this Process object has terminated." Afterwords, see if it completed successfully with Process#exitValue
.
You can also interact with the process by fetching its input and output streams:
InputStream inputStream = p.getInputStream(), errorStream = p.getErrorStream();
OutputStream outputStream = p.getOutputStream();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论