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 the Author

author image
mkyong
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

avatar
6 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
Pavan SolapurejasonNimaAdriansidd Recent comment authors
newest oldest most voted
Pavan Solapure
Guest
Pavan Solapure

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

jason
Guest
jason

very nice~~~

Nima
Guest
Nima

Wow i didnt know that

Adrian
Guest
Adrian

blah blh

sidd
Guest
sidd

ss

sidd
Guest
sidd

nice