How to Run Windows Bat File in Java


In this example we will show how to run Windows bat file.

Source Code

package com.beginner.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class RunBatExample {
  
  
      public static void main(String args[]){
	      try 
	      {
		      Process p = Runtime.getRuntime().exec("C:/example.bat");
		      
		      //read the bat file
		      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		      String line;
			  while ((line = reader.readLine()) != null) 
			  {
				    System.out.println(line);
			  }
			  reader.close();
	          p.waitFor();
	          System.out.println("done");
	      } 
	      catch (InterruptedException e) 
	      {
	    	  e.printStackTrace();
	      }
	      catch (IOException e) 
	      {
	    	  e.printStackTrace();
	      }
      }
 }

Output:

Hello World
done

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments