Jun 202018


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.


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");

	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);
	    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

	    String line = "";
	    while ((line = reader.readLine()) != null) {

	} catch (Exception e) {

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.


Execute shell commands example

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


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

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