简体   繁体   中英

Stopping the program if error is printed while running

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

I am executing two java programs one after the other as given in the above code. If any error occurs in the first program(Newsworthy_RB), my program should terminate displaying the error. Instead it continues to the execution of second program(Newsworthy_CA).

What should be done to get the error stream... Kindly advise...

You can stop the programm by explicitly calling System.exit(status) . In case of an error status should be != 0 to indicate it.

You can access the error stream via child.getErrorStream() .

EDIT: The actual answer depends on what you really want to do. If you aim is just to check, if the first programm sucessfully terminated (ended), you can write the following:

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() does the following (copied from 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.

Try

if (child.waitFor() != 0) {
    // print error message here
    return;
}

between the two executions. waitFor causes the current thread to wait until the associated process returns. See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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