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
}
-c 4
send 4 packets and -W 1
waits 1 second max for each packet.
On my email sending class, I generally have a fallback that relies on the machine sendmail/mail program. It kicks in if the SMTP server is not responding or is badly configured.
You may be interested in checking how to use sendmail (or mail) for sending emails as a one-liner.
Originally published at https://wasteofserver.com on March 1, 2023.