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 executer ls -al command by reading the
            // process's input stream
            //
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below is our program result:

exitValue = 0
total 152
drwxr-xr-x  7 root root  4096 2008-12-21 18:49 .
drwxr-xr-x 16 root root  4096 2008-12-16 14:35 ..
-rw-r--r--  1 root root  2088 2008-12-20 17:33 Examples.iml
-rw-r--r--  1 root root 16507 2008-12-20 17:33 Examples.ipr
-rw-r--r--  1 root root 37373 2008-12-21 18:49 Examples.iws
-rw-r--r--  1 root root    53 2008-11-05 16:43 hello.dat
drwxr-xr-x  2 root root  4096 2008-10-02 09:42 intext
drwxr-xr-x  2 root root  4096 2008-10-02 09:16 lib
drwxr-xr-x  5 root root  4096 2008-10-02 09:41 out
-rw-r--r--  1 root root   210 2008-11-06 12:22 sealed.dat
-rw-r--r--  1 root root   263 2008-11-06 12:22 secretkey.dat
-rw-r--r--  1 root root 45201 2008-10-02 19:53 sitemap.xml
drwxr-xr-x  3 root root  4096 2008-12-02 08:39 src
-rw-r--r--  1 root root     0 2008-10-02 18:14 Touch.dat
drwxr-xr-x  3 root root  4096 2008-10-02 09:14 web

Wayan Saryada

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

Leave a Reply