How to run a batch file from Java Program

In this tutorial, we are going to see how to run a batch file from Java Program. In Java, we can use the ProcessBuilder class to run a Windows batch file like this:

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


How to run a batch file from Java Program

The following batch file displays the message “Welcome to StackHowTo!”:

@echo off
echo Welcome to StackHowTo!

The following Java code reads the above batch file and prints the output.



public class Main {

    public static void main(String[] args) {

        ProcessBuilder pb = new ProcessBuilder("C:\\Users\\PC\\Desktop\\file.bat");
        try {
            Process p = pb.start();
            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 + "\n");

            int code = p.waitFor();
            if (code == 0) {
        } catch (Exception e) {


Welcome to StackHowTo!
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 *