简体   繁体   中英

Run a java program through java code

I am working in Linux/Ubuntu. I want to run a process in through my java code, which looks like below

ProcessBuilder pb = new ProcessBuilder("/usr/lib/flume-ng/bin/flume-ng", 
                                       "agent", 
                                       "-f", 
                                       "/home/c4/Flume/New/ClientAgent.config",
                                       "-n", 
                                       "clientAgent");
    pb.start();

But i get unreported exception java.io.IOException; must be caught or declared to be thrown pb.start(); unreported exception java.io.IOException; must be caught or declared to be thrown pb.start(); as error output. Please tell me how i can run my process. Thanks.

It's telling you the start() method could throw an Exception, and you have to deal with it . You can either:

  1. catch it and log it or otherwise handle it, or
  2. declare your method as possibly throwing this exception, and let a method higher up the stack handle it (using these two options)

The Exception object is checked , which means the compiler is concerned with it, and you need to be too (however much of a pain that is). Other exceptions are unchecked , and this means you don't have to worry. The compiler won't worry either (eg OutOfMemoryError - be aware that I'm mixing some exception terminology here, since it's a little convoluted).

Since, IOException is a checked exception you need to either catch it

try {
    pb.start();
} catch (IOException e) {
    e.printStackTrace();
}

or throw it with the enclosing method declared to do so.

public void yourMethod() throws IOException {

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