How to call a .bat script from Java?
To invoke a bat script, you can use the ProcessBuilder class in Java. Here is an example code:
import java.io.IOException;
public class CallBatScript {
public static void main(String[] args) {
try {
// 创建ProcessBuilder对象,传入要执行的命令或脚本
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path_to_bat_script.bat");
// 启动进程
Process process = pb.start();
// 等待进程执行结束
int exitCode = process.waitFor();
// 打印进程输出和错误信息(可选)
System.out.println("Exit Code: " + exitCode);
System.out.println("Standard Output: " + readStream(process.getInputStream()));
System.out.println("Error Output: " + readStream(process.getErrorStream()));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
// 读取InputStream并将其转换为字符串
private static String readStream(java.io.InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[1024];
int length;
while ((length = is.read(buf)) != -1) {
sb.append(new String(buf, 0, length));
}
return sb.toString();
}
}
Please replace path_to_bat_script.bat in the code above with the path to the bat script you want to call.