Main Tutorials

Java – How to run Windows bat file

In Java, we can use ProcessBuilder to run a Windows batch file like this :


	ProcessBuilder processBuilder = 
		new ProcessBuilder("C:\\Users\\mkyong\\hello.bat");

//or 

	ProcessBuilder processBuilder = new ProcessBuilder();
	processBuilder.command("cmd", "/c", "hello.bat");
	File dir = new File("C:\\Users\\mkyong\\");
	processBuilder.directory(dir);

Alternatively, Runtime.getRuntime().exec like this :


	Process process = Runtime.getRuntime().exec(
		"cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\"));

1. Java Example

1.1 A simple bat file.

C:\\Users\\mkyong\\hello.bat

@echo off
echo Hello World

1.2 Java example to read above bat file and display the output.

JavaRunBatFile.java

package com.mkyong.concurrency;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaRunBatFile {

    public static void main(String[] args) {

        ProcessBuilder processBuilder = new ProcessBuilder("C:\\Users\\mkyong\\hello.bat");
       
		//Process process = Runtime.getRuntime().exec(
        //            "cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\"));
					
        try {

            Process process = processBuilder.start();

            StringBuilder output = new StringBuilder();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

            int exitVal = process.waitFor();
            if (exitVal == 0) {
                System.out.println(output);
                System.exit(0);
            } else {
                //abnormal...
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

Output


Hello World

References

  1. Wikipedia – Batch file
  2. Java ProcessBuilder examples

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Pavan Solapure
4 years ago

How do I run the bat file as an Administrator from above shared Java program?

Nima
5 years ago

Wow i didnt know that

Thanh Nguyen
3 years ago

Can you help me! This code is great when run IntellIj, but I can’t run it in tomcat!

huang vivi
4 years ago

good

jason
4 years ago

very nice~~~

Adrian
5 years ago

blah blh

sidd
5 years ago

ss

sidd
5 years ago

nice