In this example, we will use ProcessBuilder to ping a website.
Source Code
package com.beginner.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessBuilderExample {
public static void main(String[] args) throws IOException, InterruptedException {
String line;
ProcessBuilder cmd = new ProcessBuilder();
// run cmd on Windows
cmd.command("cmd.exe", "/c", "ping -n 3 Yahoo.com");
Process p = cmd.start();
// process message
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
//exit message
int msg = p.waitFor();
System.out.println("Exited with msg: " + msg);
}
}
Output:
Pinging Yahoo.com [72.30.35.9] with 32 bytes of data:
Reply from 72.30.35.9: bytes=32 time=226ms TTL=47
Reply from 72.30.35.9: bytes=32 time=226ms TTL=47
Reply from 72.30.35.9: bytes=32 time=223ms TTL=47
Ping statistics for 72.30.35.9:
Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 223ms, Maximum = 226ms, Average = 225ms
Exited with msg: 0
References
Imported packages in Java documentation: