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();
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!