Run bash commands from Java

in #java2 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/

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.030
BTC 64367.46
ETH 2522.70
USDT 1.00
SBD 2.65