Home  Java   Calling win ...

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

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
Published on: Jun 26, 2024, 10:45 PM  
 

Comments

Add your comment