Java の Java Lang Runtime exec() メソッド

Sheeraz Gul 2023年10月12日
Java の Java Lang Runtime exec() メソッド

このチュートリアルでは、Java の Runtime.exec() メソッドについて説明します。

Java Lang Runtime exec() Java のメソッド

Java Lang Runtime クラスは、ランタイム クラスのインスタンスを持つすべての Java アプリケーションと環境インターフェイスとの間の対話に使用されます。 Runtime.getRuntime.exec() メソッドは、プロセス内で文字列コマンドを実行するために使用されます。

Runtime.exec() メソッドは、次の方法で実装できます。

方法 アクション
exec(文字列 cmd) これは、プロセスで文字列コマンドを実行するために使用されます。
exec(String[] cmd) これは、プロセス内で引数付きの特定のコマンドを実行するために使用されます。
exec(String command, String[] envp, File dir) これは、特定の環境とディレクトリを持つプロセスで単一の文字列コマンドを実行するために使用されます。
exec(文字列コマンド, 文字列[] envp) これは、特定の環境のプロセスで単一の文字列コマンドを実行するために使用されます。
exec(String[] cmdarray, String[] envp, File dir) これは、特定の環境とディレクトリを持つプロセスで引数付きの文字列コマンドを実行するために使用されます。
exec(String[] cmdarray, String[] envp) これは、特定の環境のプロセスで引数付きの文字列コマンドを実行するために使用されます。

Java で Runtime.exec() メソッドを実装する例を試してみましょう。

package delftstack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

// Main class
public class Example {
  // Main driver method
  public static void main(String[] args) throws InterruptedException {
    try {
      // Use Runtime.getRuntime.exec on a separate process
      Process Demo_Process = Runtime.getRuntime().exec("java -version");

      // Get the output in the console

      String Output_Line;
      InputStreamReader Input_Stream_Reader = new InputStreamReader(Demo_Process.getInputStream());
      BufferedReader Buffered_Reader = new BufferedReader(Input_Stream_Reader);
      while ((Output_Line = Buffered_Reader.readLine()) != null) {
        System.out.println(Output_Line);
      }

      Input_Stream_Reader = new InputStreamReader(Demo_Process.getErrorStream());
      Buffered_Reader = new BufferedReader(Input_Stream_Reader);
      while ((Output_Line = Buffered_Reader.readLine()) != null) {
        System.out.println(Output_Line);
      }
      // Wait for the process to complete
      Demo_Process.waitFor();

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

上記のコードは、メソッド Runtime.getRuntime.exec()java -version コマンドで実行し、コンソールに出力を取得します。 出力を見る

java version "17.0.2" 2022-01-18 LTS
Java(TM) SE Runtime Environment (build 17.0.2+8-LTS-86)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.2+8-LTS-86, mixed mode, sharing)
著者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook