gpt4 book ai didi

java - 如果运行时打印错误则停止程序

转载 作者:行者123 更新时间:2023-12-02 08:30:46 25 4
gpt4 key购买 nike

import java.lang.Process;        
import java.io.*;
import java.io.InuputStream;
import java.io.IOException;

public class newsmail{
public static void main(String[] args) throws IOException{
String command = "java Newsworthy_RB";
Process child = Runtime.getRuntime.exec(command);
int c;
InputStream in = child.getInputStream();
while((c=in.read())!=-1){
System.out.print((char)c);
}
in.close();

command = "java Newsworthy_CA";
Process child = Runtime.getRuntime.exec(command);
InputStream in = child.getInputStream();
while((c=in.read())!=-1){
System.out.print((char)c);
}
in.close();
}

我正在一个接一个地执行两个java程序,如上面的代码所示。如果第一个程序(Newsworthy_RB)中发生任何错误,我的程序应该终止显示错误。相反,它继续执行第二个程序(Newsworthy_CA)。

应该如何获取错误流...请建议...

最佳答案

您可以通过显式调用System.exit(status)来停止程序。如果出现错误,状态应为 != 0 来指示。

您可以通过child.getErrorStream()访问错误流。

编辑:实际答案取决于您真正想要做什么。如果您的目的只是检查第一个程序是否成功终止(结束),您可以编写以下内容:

public static void main(String[] args) throws Exception {
Process child1 = Runtime.getRuntime().exec("cmd");
int status1 = child1.waitFor();

System.out.println("Exit status of child one: " + status1);

// Something has gone wrong
if (status1 != 0) {
// end program
return;
}

Process child2 = Runtime.getRuntime().exec("cmd2");
int status2 = child2.waitFor();

System.out.println("Exit status of child two: " + status2);
}

Process#waitFor() 执行以下操作(从 javadoc 复制):

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

关于java - 如果运行时打印错误则停止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com