Jun 202018

ADM

How to execute shell command from Java

  • 20 June 2018
  • ADM

 

 

 

How to execute shell command from Java - images/logos/java.jpg

 

If you need to run a command line application from Java you can use Runtime.getRuntime().exec() method.

Code

Here is a simple code on how to execute a shell command from Java. As a sample command, it is used the ping command and the example was tested using Windows 10.

Note: depending on your system configuration you might need permission to run a specific command.

package com.admfactory.io;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellCommandExample {
    public static void main(String[] args) {
	System.out.println("Execute shell commands example");
	System.out.println();

	try {
	    String cmd = "ping admfactory.com";
	    System.out.println("Executing command: " + cmd);
	    Process p = Runtime.getRuntime().exec(cmd);
	    int result = p.waitFor();
	    
	    System.out.println("Process exit code: " + result);
	    System.out.println();
	    System.out.println("Result:");
	    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

	    String line = "";
	    while ((line = reader.readLine()) != null) {
		System.out.println(line);
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}

Note: the ping command run 4 times by default if you are using Windows. On Linux and MacOS you need to add the -c parameter to specify how many times to try.

Output

Execute shell commands example

Executing command: ping admfactory.com
Process exit code: 0

Result:

Pinging admfactory.com [104.31.90.143] with 32 bytes of data:
Reply from 104.31.90.143: bytes=32 time=27ms TTL=56
Reply from 104.31.90.143: bytes=32 time=25ms TTL=56
Reply from 104.31.90.143: bytes=32 time=23ms TTL=56
Reply from 104.31.90.143: bytes=32 time=25ms TTL=56

Ping statistics for 104.31.90.143:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 23ms, Maximum = 27ms, Average = 25ms

 

 

 

References