温馨提示×

java怎么调用批处理文件

小亿
92
2023-12-05 10:27:25
栏目: 编程语言

在Java中,可以使用Runtime类的exec()方法执行批处理文件。

以下是一个简单的示例:

public class CallBatchFile {
    public static void main(String[] args) {
        try {
            // 调用批处理文件
            Process process = Runtime.getRuntime().exec("path_to_batch_file.bat");

            // 获取批处理文件的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待批处理文件执行完毕
            int exitCode = process.waitFor();
            System.out.println("Exit Code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

请将path_to_batch_file.bat替换为实际的批处理文件路径。运行以上代码将调用批处理文件并打印出其输出。

0