有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果运行时打印错误,java将停止程序

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程序。 如果第一个程序(有新闻价值的)出现任何错误,我的程序应该终止显示错误。相反,它继续执行第二个程序(有新闻价值的_CA)

应该做些什么来获取错误流。。。请告知


共 (1) 个答案

  1. # 1 楼答案

    可以通过显式调用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.