Java - Execute external command

By xngo on June 30, 2019

The code example below will run the following external commands:

  • dir > test_out.txt: If you are on MS Windows.
  • ls > test_out.txt: If you are on other operating system, e.g. Linux, Unix, MacOS, etc.
import java.io.IOException;
 
public class CmdExecution {
 
    public static void main(String[] args) {
        // Get the appropriate command depending on the operating system.
        String os_name = System.getProperty("os.name");
        String cmdLine[];
        if (os_name.indexOf("Windows") != -1)
            cmdLine = new String[] { "cmd", "/c", "dir > .\\test_out.txt" }; // dir > test_out.txt
        else
            cmdLine = new String[] { "/bin/sh", "-c", "ls > ./test_out.txt" }; // ls > test_out.txt
 
        try {
 
            // Print what will be run.
            System.out.println("Running on "+os_name+": ");
            System.out.print("\t");
            for (String str : cmdLine)
                System.out.print(str + " ");
            System.out.println();
 
            // Execute the command.
            Process process = Runtime.getRuntime().exec(cmdLine);
 
            try {
                process.waitFor();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } // Wait for the process to terminate.
            if (process.exitValue() == 0)
                System.out.println("\texitValue: true");
            else
                System.out.println("\texitValue: false");
 
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
    }
 
}

Output

Running on Linux: 
    /bin/sh -c ls > ./test_out.txt 
    exitValue: true

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/io/CmdExecution.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.