java

How to run a batch file from Java Program

In this tutorial, we’ll see how to run a .bat (batch) file from a Java program using the ProcessBuilder class. This is useful for automating system tasks from Java applications.

ProcessBuilder pb = new ProcessBuilder("C:\\Users\\PC\\Desktop\\file.bat");

 
 

🧾 Example Batch File

Create a batch file called file.bat with the following content. This file will simply display a message:

@echo off
echo Welcome to StackHowTo!

Save this file on your desktop, e.g., at:

C:\Users\PC\Desktop\file.bat

 

🧑‍💻 Java Code to Execute the Batch File

Here is the Java code that executes the batch file and prints its output to the console:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        // Specify the path to your batch file
        ProcessBuilder pb = new ProcessBuilder("C:\\Users\\PC\\Desktop\\file.bat");

        try {
            // Start the process
            Process p = pb.start();

            // Read the process output
            StringBuilder str = new StringBuilder();
            InputStreamReader isr = new InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(isr);

            String line;
            while ((line = br.readLine()) != null) {
                str.append(line).append("\n");
            }

            // Wait for the process to complete
            int code = p.waitFor();

            // Display output if process was successful
            if (code == 0) {
                System.out.println(str);
                System.exit(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

🖥️ Output:

Welcome to StackHowTo!

🧠 Notes:

  • Adjust the path to your .bat file if it’s located elsewhere.
  • You can also merge the error stream with the output stream using: pb.redirectErrorStream(true);
  • ProcessBuilder can run any command-line script or executable — not just .bat files.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *