javaからバッチファイルを実行の方法

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 を実際のバッチファイルのパスに置き換えてください。上記コードを実行すると、バッチファイルが呼び出され、その出力が表示されます。

bannerAds