How to Execute External Scripts from Java Applications
Prepare the external script file you intend to run first. For demonstration, we use a bash script named sample_task.sh with the following content:
#!/bin/bash
echo "Script execution initiated"
ls -l ./working_dir
echo "Script run completed without errors"
exit 0
Grant execution permission to the script with chmod +x sample_task.sh before invoking it from your Java code.
Trigger script execution via the Java Runtime API with the flolowing snippet. The code defines the execution command, launches the script process, and waits for the process to finish running:
String runCmd = "sh sample_task.sh";
Process scriptProcess = Runtime.getRuntime().exec(runCmd);
int executionExitCode = scriptProcess.waitFor();
The executionExitCode value returns the exit status of the script, where 0 represents successful execution, and any non-zero value indicates an exectuion failure.
To capture and process standard output generated by the script, read data from the process's input stream. You can also read from the process's error stream to collect debug information for failed runs:
List<String> standardOutput = new ArrayList<>();
BufferedReader outputReader = new BufferedReader(
new InputStreamReader(scriptProcess.getInputStream())
);
String lineContent;
while ((lineContent = outputReader.readLine()) != null) {
standardOutput.add(lineContent);
}
// Collect error output for troubleshooting
List<String> errorOutput = new ArrayList<>();
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(scriptProcess.getErrorStream())
);
while ((lineContent = errorReader.readLine()) != null) {
errorOutput.add(lineContent);
}
Adjust the execution command to match you're target script type:
- For Python scripts: use
python3 your_script.pyas the comand value - For Windows batch files: use
cmd /c your_script.batas the command value - For Node.js scripts: use
node your_script.jsas the comand value