How do I execute external command and obtain the result?

This example demonstrate how to execute an external command from Java and obtain the result of the command. Here we simple execute a Linux ls -al command on the current working directory and display the result.

package org.kodejava.example.lang;

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

public class ProcessResult {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("ls -al");

            // Wait for this process to finish or terminated
            process.waitFor();

            // Get process exit value
            int exitValue = process.exitValue();
            System.out.println("exitValue = " + exitValue);

            // Read the result of the ls -al command by reading the
            // process's input stream
            InputStreamReader is = new InputStreamReader(process.getInputStream());
            BufferedReader reader = new BufferedReader(is);
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below is our program result:

exitValue = 0
total 64
drwxr-xr-x  20 wsaryada  staff   680 Aug  7 14:13 .
drwxr-xr-x   4 wsaryada  staff   136 Jun 18 00:33 ..
-rw-r--r--@  1 wsaryada  staff  6148 Jun 29 14:04 .DS_Store
-rw-r--r--   1 wsaryada  staff   267 May 19 20:47 .editorconfig
drwxr-xr-x  16 wsaryada  staff   544 Aug 10 08:34 .git
-rw-r--r--   1 wsaryada  staff  1535 May 19 20:47 .gitignore
drwxr-xr-x  15 wsaryada  staff   510 Aug 10 08:34 .idea
-rw-r--r--   1 wsaryada  staff  1313 May 19 20:47 LICENSE
-rw-r--r--   1 wsaryada  staff   101 May 19 20:47 README.md
drwxr-xr-x   5 wsaryada  staff   170 Jul 28 23:11 kodejava-basic
drwxr-xr-x   6 wsaryada  staff   204 Jun 30 14:22 kodejava-commons
drwxr-xr-x   6 wsaryada  staff   204 Jul 27 15:32 kodejava-lang-package
drwxr-xr-x@  5 wsaryada  staff   170 Jun 16 20:49 kodejava-mail
drwxr-xr-x   6 wsaryada  staff   204 Aug  7 17:22 kodejava-mybatis
drwxr-xr-x   5 wsaryada  staff   170 Jul 20 10:36 kodejava-poi
-rw-r--r--   1 wsaryada  staff   669 Jun  2 14:29 kodejava-project.iml
drwxr-xr-x   7 wsaryada  staff   238 Jun 26 21:52 kodejava-swing
drwxr-xr-x   6 wsaryada  staff   204 Aug  3 15:06 kodejava-util-package
drwxr-xr-x   6 wsaryada  staff   204 Jun 30 15:09 maven-helloworld
-rw-r--r--   1 wsaryada  staff  1622 Aug  7 14:13 pom.xml

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply