Java Runtime exec() 方法



描述

Java Runtime exec(String command, String[] envp) 方法在單獨的程序中使用指定的環境執行指定的字串命令。這是一種便捷方法。形式為 exec(command, envp) 的呼叫與呼叫 exec(command, envp, null) 的行為完全相同。

宣告

以下是 java.lang.Runtime.exec() 方法的宣告

public Process exec(String command, String[] envp)

引數

  • command − 指定的系統命令。

  • envp − 字串陣列,每個元素都以 name=value 的格式包含環境變數設定,或者如果子程序應該繼承當前程序的環境則為 null。

返回值

此方法返回一個新的 Process 物件,用於管理子程序

異常

  • SecurityException − 如果存在安全管理器並且其 checkExec 方法不允許建立子程序

  • IOException − 如果發生 I/O 錯誤

  • NullPointerException − 如果 command 為 null,或者 envp 的某個元素為 null

  • IllegalArgumentException − 如果 command 為空

示例:開啟記事本應用程式

以下示例顯示了 Java Runtime exec() 方法的使用。我們使用 exec() 方法為記事本可執行檔案建立了一個 Process 物件。這將呼叫記事本應用程式。如果發生某些異常,則會列印相應的堆疊跟蹤和錯誤訊息。

package com.tutorialspoint;

import java.io.File;

public class RuntimeDemo {

   public static void main(String[] args) {
      try {

         // print a message
         System.out.println("Executing notepad.exe...");

         // create a process and execute notepad.exe and currect environment
         Process process = Runtime.getRuntime().exec("notepad.exe", null);

         // print another message
         System.out.println("Notepad should now open.");

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

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Executing notepad.exe...
Notepad should now open.

示例:開啟計算器應用程式

以下示例顯示了 Java Runtime exec() 方法的使用。我們使用 exec() 方法為 calc 可執行檔案建立了一個 Process 物件。這將呼叫計算器應用程式。如果發生某些異常,則會列印相應的堆疊跟蹤和錯誤訊息。

package com.tutorialspoint;

public class RuntimeDemo {

   public static void main(String[] args) {
      try {

         // print a message
         System.out.println("Executing calc.exe...");

         // create a process and execute calc.exe and currect environment
         Process process = Runtime.getRuntime().exec("calc.exe", null);

         // print another message
         System.out.println("Calculator should now open.");

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

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Executing calc.exe...
Calculator should now open.

示例:開啟 Windows 資源管理器應用程式

以下示例顯示了 Java Runtime exec() 方法的使用。我們使用 exec() 方法為 Windows 資源管理器可執行檔案建立了一個 Process 物件。這將呼叫 Windows 資源管理器應用程式。如果發生某些異常,則會列印相應的堆疊跟蹤和錯誤訊息。

package com.tutorialspoint;

public class RuntimeDemo {

   public static void main(String[] args) {
      try {

         // print a message
         System.out.println("Executing explorer.exe...");

         // create a process and execute calc.exe and currect environment
         Process process = Runtime.getRuntime().exec("explorer.exe", null);

         // print another message
         System.out.println("Windows Explorer should now open.");

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

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Executing explorer.exe...
Windows Explorer should now open.
java_lang_runtime.htm
廣告