溫馨提示×

java怎么調(diào)用bat腳本

小億
275
2024-01-22 11:13:10
欄目: 編程語言

要調(diào)用bat腳本,可以使用Java的ProcessBuilder類。下面是一個示例代碼:

import java.io.IOException;

public class CallBatScript {
    public static void main(String[] args) {
        try {
            // 創(chuàng)建ProcessBuilder對象,傳入要執(zhí)行的命令或腳本
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path_to_bat_script.bat");
            // 啟動進程
            Process process = pb.start();
            
            // 等待進程執(zhí)行結(jié)束
            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并將其轉(zhuǎn)換為字符串
    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替換為你要調(diào)用的bat腳本的路徑。

0