[Java]exec()で外部プロセスを起動するサンプル

2021年8月23日

書式
1.public static Runtime getRuntime()
現在のJavaアプリケーションに関連したRuntimeオブジェクトを返します。
2.public Process exec(String command)throws IOException
指定された文字列コマンドを、独立したプロセスで実行します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.info;
import java.io.IOException;
public class RedirectStreDemo {
public static void main(String[] args) throws IOException, InterruptedException {
Runtime r = Runtime.getRuntime();
/* コマンドの文字列を引数付き コマンドが実行 */
Process process = r.exec("java -version");
/* 起動プロセス */
int ret = process.waitFor();
System.out.println("終了コード1: " + ret);
process.waitFor();
int ret2 = process.exitValue();
System.out.println("終了コード2: " + ret2);
}
}
package com.arkgame.info; import java.io.IOException; public class RedirectStreDemo { public static void main(String[] args) throws IOException, InterruptedException { Runtime r = Runtime.getRuntime(); /* コマンドの文字列を引数付き コマンドが実行 */ Process process = r.exec("java -version"); /* 起動プロセス */ int ret = process.waitFor(); System.out.println("終了コード1: " + ret); process.waitFor(); int ret2 = process.exitValue(); System.out.println("終了コード2: " + ret2); } }
package com.arkgame.info;

import java.io.IOException;

public class RedirectStreDemo {

      public static void main(String[] args) throws IOException, InterruptedException {
            Runtime r = Runtime.getRuntime();

            /* コマンドの文字列を引数付き コマンドが実行 */
            Process process = r.exec("java -version");

            /* 起動プロセス */
            int ret = process.waitFor();
            System.out.println("終了コード1:  " + ret);

            process.waitFor();
            int ret2 = process.exitValue();
            System.out.println("終了コード2: " + ret2);
      }

}

実行結果
終了コード1: 0
終了コード2: 0

Java

Posted by arkgame