How can a bat file be started using Java?

To execute a .bat file in Java, you can use the exec() method of the Runtime class. Here is an example code:

import java.io.IOException;

public class ExecuteBatFile {
    public static void main(String[] args) {
        try {
            // 指定.bat文件的路径
            String batFilePath = "C:/path/to/your/file.bat";
            
            // 执行.bat文件
            Process process = Runtime.getRuntime().exec("cmd /c start " + batFilePath);
            
            // 等待.bat文件执行完成
            int exitCode = process.waitFor();
            
            // 打印.bat文件的退出码
            System.out.println("Exit Code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Please make sure to replace the batFilePath variable with the actual path of your .bat file. The “cmd /c start” part is used to start the .bat file on Windows. If you are running on a different operating system, you will need to modify this part of the code accordingly.

bannerAds