Java查找批处理文件是否成功运行

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月3日 20:18:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63723524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定