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();
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap