Java ProcessBuilder start() 方法



描述

Java ProcessBuilder start() 方法使用此程序構建器的屬性啟動一個新程序。新程序將呼叫由 command() 給出的命令和引數,在由 directory() 給出的工作目錄中,使用由 environment() 給出的程序環境。此方法檢查命令是否為有效的作業系統命令。哪些命令有效取決於系統,但至少命令必須是非空且非 null 字串的列表。

如果存在安全管理器,則其 checkExec 方法將使用此物件的 command 陣列的第一個元件作為其引數被呼叫。這可能會導致丟擲 SecurityException。

宣告

以下是 java.lang.ProcessBuilder.start() 方法的宣告

public Process start()

引數

返回值

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

異常

  • NullPointerException − 如果命令列表中的元素為 null

  • IndexOutOfBoundsException − 如果命令為空列表(大小為 0)

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

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

使用 Process Builder 示例啟動記事本程序

以下示例演示了 ProcessBuilder start() 方法的使用。在此程式中,我們建立了一個字串陣列,並將 notepad.exe 和 test.txt 新增到其中。使用該列表,我們初始化了一個 ProcessBuilder 例項。現在使用 start() 方法,我們啟動了程序。

package com.tutorialspoint;

import java.io.IOException;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      String[] list = {"notepad.exe", "test.txt"};

      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);
      try {
         // start the subprocess
         System.out.println("Starting the process..");
         pb.start();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

輸出

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

Starting the process..

使用 Process Builder 示例啟動計算器程序

以下示例演示了 ProcessBuilder start() 方法的使用。在此程式中,我們建立了一個字串陣列,並將 calc.exe 新增到其中。使用該列表,我們初始化了一個 ProcessBuilder 例項。現在使用 start() 方法,我們啟動了程序。

package com.tutorialspoint;

import java.io.IOException;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      String[] list = {"calc.exe"};

      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);
      try {
         // start the subprocess
         System.out.println("Starting the process..");
         pb.start();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

輸出

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

Starting the process..

使用 Process Builder 示例啟動 Windows 資源管理器程序

以下示例演示了 ProcessBuilder start() 方法的使用。在此程式中,我們建立了一個字串陣列,並將 explorer.exe 新增到其中。使用該列表,我們初始化了一個 ProcessBuilder 例項。現在使用 start() 方法,我們啟動了程序。

package com.tutorialspoint;

import java.io.IOException;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      String[] list = {"explorer.exe"};

      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);
      try {
         // start the subprocess
         System.out.println("Starting the process..");
         pb.start();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

輸出

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

Starting the process..
java_lang_processbuilder.htm
廣告