Java Runtime exec() 方法



描述

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

宣告

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

public Process exec(String command)

引數

command − 指定的系統命令。

返回值

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

異常

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

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

  • NullPointerException − 如果 command 為 null。

  • IllegalArgumentException − 如果 command 為空。

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

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

package com.tutorialspoint;

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
         Process process = Runtime.getRuntime().exec("notepad.exe");

         // 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() 方法為計算器可執行檔案建立了一個 Process 物件。這將呼叫計算器應用程式。如果發生某些異常,則會列印相應的堆疊跟蹤以及錯誤訊息。

package com.tutorialspoint;

public class RuntimeDemo {

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

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

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

         // 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() 方法為 explorer 可執行檔案建立了一個 Process 物件。這將呼叫 explorer 應用程式。如果發生某些異常,則會列印相應的堆疊跟蹤以及錯誤訊息。

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 explorer.exe
         Process process = Runtime.getRuntime().exec("explorer.exe");

         // 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
廣告

© . All rights reserved.