温馨提示×

java怎么调用bat脚本

小亿
277
2024-01-22 11:13:10
栏目: 编程语言

要调用bat脚本,可以使用Java的ProcessBuilder类。下面是一个示例代码:

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();
    }
}

请将上述代码中的path_to_bat_script.bat替换为你要调用的bat脚本的路径。

0