Ways to execute Shell Commands in Java Code Examples

Example 1: Runtime.exec()
try {
    String command = "ls -l";
    Process process = Runtime.getRuntime().exec(command);

    int exitCode = process.waitFor(); // Wait for command to complete
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

Example 2: ProcessBuilder
try {
    String command = "ls -ltrh"; 
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    Process process = processBuilder.start();

    int exitCode = process.waitFor();
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

Example 3: Apache Commons: org.apache.commons.exec.*
try {
    String command = "ps -ef"; 
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = executor.execute(cmdLine);
} catch (ExecuteException | IOException e) {
    e.printStackTrace();
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!