Calling windows batch script from Java - Handling exit code
Windows processes return exit codes similar to Linux processes. The exit code of a process indicates the status of its termination. Typically, an exit code of 0 indicates successful completion, while any non-zero exit code indicates an error or abnormal termination.
Example: Checking Exit Codes in Windows
To illustrate this, let's create a simple batch script and a Java program to invoke it and capture its exit code.
Step 1: Create a Batch Script
Save the following content as example.bat:
@echo off
echo Hello from the batch script
exit /b 0
This script prints a message and then exits with a code of 0.
Step 2: Modify the Batch Script to Return Different Exit Codes
Modify the script to simulate an error:
@echo off
echo This script will fail
exit /b 1
This script prints an error message and then exits with a code of 1.
Step 3: Java Code to Invoke the Batch Script
Here is the Java code to invoke the batch script and capture its exit code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ProcessLauncher {
public static void main(String[] args) {
ProcessLauncher launcher = new ProcessLauncher();
String scriptPath = "example.bat"; // Adjust the path to your batch script
ProcessResult result = launcher.runScript(scriptPath);
if (result.getExitCode() == 0) {
System.out.println("Script succeeded. Output:");
} else {
System.out.println("Script failed with exit code: " + result.getExitCode());
}
System.out.println(result.getOutput());
}
public ProcessResult runScript(String scriptPath) {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", scriptPath);
processBuilder.redirectErrorStream(true);
StringBuilder output = new StringBuilder();
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
int exitCode = process.waitFor();
return new ProcessResult(exitCode, output.toString());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return new ProcessResult(-1, e.getMessage());
}
}
}
class ProcessResult {
private int exitCode;
private String output;
public ProcessResult(int exitCode, String output) {
this.exitCode = exitCode;
this.output = output;
}
public int getExitCode() {
return exitCode;
}
public String getOutput() {
return output;
}
@Override
public String toString() {
return "ProcessResult{" +
"exitCode=" + exitCode +
", output='" + output + '\'' +
'}';
}
}
Explanation
- Batch Script: The batch script (
example.bat) is a simple script that prints a message and exits with a specified code. - ProcessBuilder: The
ProcessBuilderclass in Java is used to create and start the process. The commandcmd.exe /c scriptPathruns the batch script. - BufferedReader: Captures the output of the batch script.
- Process.waitFor(): Waits for the process to complete and returns the exit code.
- ProcessResult Class: Encapsulates the exit code and output of the process.
Output
When you run the Java program with the first version of the batch script (which exits with code 0), you should see:
Script succeeded. Output:
Hello from the batch script
When you run the Java program with the second version of the batch script (which exits with code 1), you should see:
Script failed with exit code: 1
This script will fail