Java - Execute Shell Command Using Process Builder - MacOs

By Softorks | August 20, 2019 | Updated : August 20, 2019

English | French

ProcessBuilder - in Java provides the ability to programatically execute shell command.

1. ProcessBuilder - Implementation

In this example, we will execute a ping command to google.com and display the response on the console.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExecuteShellComandProcessBuilder {
    public static void main (String [] args) throws IOException, InterruptedException{
        
        String [] command = {"ping", "google.com"};
        
        ProcessBuilder processBuilder = new ProcessBuilder(command); 
        processBuilder.directory(new File(System.getProperty("user.home")));
        
        try {
            Process process = processBuilder.start();
            
            BufferedReader reader = 
                new BufferedReader (new InputStreamReader(process.getInputStream()));
            
            String line;
            
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            
            int exitCode = process.waitFor(); 
            
            System.out.println ("\nExited with error code : " + exitCode);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
                        

Output:

vpn-133-230-1-300:~ softorks$ ping google.com
PING google.com (216.58.193.142): 56 data bytes
64 bytes from 216.58.193.142: icmp_seq=0 ttl=52 time=34.190 ms
64 bytes from 216.58.193.142: icmp_seq=1 ttl=52 time=32.910 ms
64 bytes from 216.58.193.142: icmp_seq=2 ttl=52 time=34.361 ms
64 bytes from 216.58.193.142: icmp_seq=3 ttl=52 time=33.286 ms

--- google.com ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 32.910/33.687/34.361/0.607 ms
vpn-133-230-1-300:~ softorks$ 
                        

2. Show Running Processes Example

In this example, we will execute the ps command to show all the running processes, their owners and processes not attached to a terminal

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class ListDirectories {
    public static void main (String [] args) {
        
        String [] listDirectoryCommand = {"ps", "aux"};
        
        ProcessBuilder pB = new ProcessBuilder(listDirectoryCommand); 
        pB.directory(new File(System.getProperty("user.home")));
        
        try {
            Process p = pB.start();
            
            BufferedReader readOutput = 
                new BufferedReader (new InputStreamReader(p.getInputStream()));
            
            String outputCommandLine;
            
            while ((outputCommandLine = readOutput.readLine()) != null) {
                System.out.println(outputCommandLine);
            }
            
            int exitCode = p.waitFor(); 
            
            System.out.println ("\nExited with error code : " + exitCode);
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
                        

Output:

root         91106   0.0  0.3  4682880  51644   ??  Ss   Mon10AM  10:38.42 /.../... aaa socket
softorks     87125   0.0  0.0  4434696   5616   ??  Ss   Mon09AM   1:06.66 /.../.../FinderSync
root         82265   0.0  0.0  4351464      8   ??  Ss   Mon08AM   0:00.03 /.../.../..ManagerService
softorks     81331   0.0  0.0  4404032   4684   ??  S    Mon04AM   0:44.65 /.../.../talagent
softorks     77742   0.0  0.0  4377756    560   ??  Ss   Sun09PM   0:00.14 /.../.ClientScripter
softorks     76864   0.0  0.0  4436844   5596   ??  Ss   Sun09PM   1:13.50 /.../.../FinderSync
softorks     76863   0.0  0.0  4849036      8   ??  Ss   Sun09PM   0:00.14 /.../.../MTLCompilerService
softorks     76861   0.0  0.0  4841384      8   ??  Ss   Sun09PM   0:00.18 /.../.../MTLCompilerService
softorks     76859   0.0  0.1  5033148  15108   ??  Ss   Sun09PM   4:08.31 /.../...PanelService

                        

3. Watch Video Tutorial...