Run bash commands from Java

in java •  2 years ago 

As one of Java paradigms is "write once, run anywhere", and calling external software makes that much more complicated, you'll want to steer away from it as much as possible. However, sometimes there's really no other viable option.

The example below shows how to ping a host and capture both the standard and the error output streams.

String cmd = "ping -c 4 -W 1 8.8.8.8"

try {
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process process = pb.start();
    process.waitFor(10, TimeUnit.SECONDS);
    try (BufferedReader br = new BufferedReader(
        new InputStreamReader(process.getInputStream())
    )) {
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line);
        }
        if (process.exitValue() != 0) {
            // mail sending failed, error is on stringBuilder
        }
    }
} catch (IOException | InterruptedException e) {
    // recover / etc
}

Read the full version on https://wasteofserver.com/call-external-command-from-java/

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!