If you are a programmer then you have to perform Ping operation multiple times everyday during some manual testing or using automated JUnit testing.
Here at Crunchify, we have published multiple Java tutorials so far. We so far received multiple request to implement a Java tutorial on Linux Ping command and here it is.
Idea is very simple:
- We will create class
LinuxPingInJava.java
- In main() method use Java Runtime utility to get runtime object.
- Create Process object to execute command
ping crunchify.com
- Get Stream result -> Parse result using BufferReader -> Print result on console
package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Crunchify.com * Implement Linux Ping Utility in Java */ public class LinuxPingInJava { private class crunchifyResultFromCommand extends Thread { InputStream inputStream = null; // This abstract class is the superclass of all classes representing an input stream of bytes. crunchifyResultFromCommand(InputStream is, String type) { this.inputStream = is; } public void run() { String crunchifyString = null; try { // Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); while ((crunchifyString = br.readLine()) != null) { System.out.println(crunchifyString); } } catch (IOException ioException) { ioException.printStackTrace(); } } } public crunchifyResultFromCommand getStreamResult(InputStream inputStream, String type) { return new crunchifyResultFromCommand(inputStream, type); } public static void main(String[] args) { // Returns the runtime object associated with the current Java application. Runtime crunchifyRuntime = Runtime.getRuntime(); LinuxPingInJava rte = new LinuxPingInJava(); crunchifyResultFromCommand crunchifyError, crunchifyResult; try { // Process proc = rt.exec("curl -v https://www.google.com"); Process proc1 = crunchifyRuntime.exec("ping crunchify.com"); crunchifyError = rte.getStreamResult(proc1.getErrorStream(), "ERROR"); crunchifyResult = rte.getStreamResult(proc1.getInputStream(), "OUTPUT"); crunchifyError.start(); crunchifyResult.start(); // Signals that an I/O exception of some sort has occurred. } catch (IOException exception) { exception.printStackTrace(); } } }
Once you run above Java Program, you should be able to see result like this:
PING crunchify.com (45.33.15.213): 56 data bytes 64 bytes from 45.33.15.213: icmp_seq=0 ttl=55 time=90.163 ms 64 bytes from 45.33.15.213: icmp_seq=1 ttl=55 time=89.469 ms 64 bytes from 45.33.15.213: icmp_seq=2 ttl=55 time=89.766 ms 64 bytes from 45.33.15.213: icmp_seq=3 ttl=55 time=88.897 ms 64 bytes from 45.33.15.213: icmp_seq=4 ttl=55 time=91.140 ms 64 bytes from 45.33.15.213: icmp_seq=5 ttl=55 time=89.950 ms