Java How to run Windows bat file
By:Roy.LiuLast updated:2019-08-11
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
From:一号门
COMMENTS