當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.lang.ProcessBuilder用法及代碼示例


該類用於創建操作係統進程。每個ProcessBuilder實例管理一組進程屬性。 start() 方法使用這些屬性創建一個新的 Process 實例。可以從同一實例重複調用 start() 方法,以創建具有相同或相關屬性的新子流程。

  • ProcessBuilder 可用於幫助創建操作係統進程。
  • 在 JDK 5.0 之前,創建進程並執行它的唯一方法是使用 Runtime.exec() 方法。
  • 它擴展了對象類。
  • 該類不同步。

構造函數:

  • ProcessBuilder(列表命令):這將使用指定的操作係統程序和參數構造一個進程構建器。
  • ProcessBuilder(字符串...命令):這將使用指定的操作係統程序和參數構造一個進程構建器。

方法:

1. List command():該方法返回進程構建器的操作係統程序和參數。

Syntax: public List command().
Returns: this process builder's program and its arguments.
Exceptions: NullPointerException - if the argument is null.

Java


// Java code illustrating command() method
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating list of process
        List<String> list = new ArrayList<String>();
        list.add("notepad.exe");
        // create the process
        ProcessBuilder build = new ProcessBuilder(list);
        // checking the command i list
        System.out.println("command: " + build.command());
    }
}
輸出
command: [notepad.exe]

2.ProcessBuilder命令(列表命令):該方法設置進程構建器的操作係統程序和參數。

Syntax: public ProcessBuilder command(List command).
Returns: NA.
Exception: NullPointerException - if the argument is null.

Java


// Java code illustrating ProcessBuilder
// command(List<String> command)
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating list of process
        List<String> list = new ArrayList<String>();
        list.add("notepad.exe");
        list.add("xyz.txt");
        // create the process
        ProcessBuilder build = new ProcessBuilder(list);
        // checking the command in list
        System.out.println("command: " + build.command());
    }
}
輸出
command: [notepad.exe, xyz.txt]

3. ProcessBuilder目錄(文件目錄):該方法設置進程構建器的工作目錄。隨後由對象的 start() 方法啟動的子進程將使用它作為工作目錄。該參數可以為 null - 表示使用當前 Java 進程的工作目錄,通常是係統屬性 user.dir 命名的目錄,作為子進程的工作目錄。

Syntax: public ProcessBuilder directory(File directory).
Returns: this process builder.
Exception: NA.

Java


// Java code illustrating directory() method
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating list of process
        List<String> list = new ArrayList<String>();
        list.add("notepad.exe");
        list.add("abc.txt");
        // creating the process
        ProcessBuilder build = new ProcessBuilder(list);
        // setting the directory
        build.directory(new File("src"));
        // checking the directory, on which currently
        // working on
        System.out.println("directory: "
                           + build.directory());
    }
}
輸出
directory: src

4. Map environment():此方法返回流程構建器環境的字符串映射視圖。每當創建流程構建器時,環境都會初始化為當前流程環境的副本。隨後由對象的 start() 方法啟動的子進程將使用此映射作為其環境。

Syntax: public Map environment()
Returns: this process builder's environment
Exception: SecurityException - if a security manager exists 
and its checkPermission method doesn't allow access to the process environment.

Java


// Java code illustrating environment() method
import java.io.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating the process
        ProcessBuilder pb = new ProcessBuilder();
        // map view of this process builder's environment
        Map<String, String> envMap = pb.environment();
        // checking map view of environment
        for (Map.Entry<String, String> entry :
             envMap.entrySet()) {
            // checking key and value separately
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}

輸出:

Key = PATH, Value = /usr/bin:/bin:/usr/sbin:/sbin
Key = JAVA_MAIN_CLASS_14267, Value = ProcessBuilderDemo
Key = J2D_PIXMAPS, Value = shared
Key = SHELL, Value = /bin/bash
Key = JAVA_MAIN_CLASS_11858, Value = org.netbeans.Main
Key = USER, Value = abhishekverma
Key = TMPDIR, Value = /var/folders/9z/p63ysmfd797clc0468vvy4980000gn/T/
Key = SSH_AUTH_SOCK, Value = /private/tmp/com.apple.launchd.uWvCfYQWBP/Listeners
Key = XPC_FLAGS, Value = 0x0
Key = LD_LIBRARY_PATH, Value = /Library/Java/JavaVirtualMachines
/jdk1.8.0_121.jdk/Contents/Home/jre/lib/
amd64:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk
/Contents/Home/jre/lib/i386:
Key = __CF_USER_TEXT_ENCODING, Value = 0x1F5:0x0:0x0
Key = Apple_PubSub_Socket_Render, Value = /private/tmp/com.apple.launchd.weuNq4pAfF/Render
Key = LOGNAME, Value = abhishekverma
Key = LC_CTYPE, Value = UTF-8
Key = XPC_SERVICE_NAME, Value = 0
Key = PWD, Value = /
Key = SHLVL, Value = 1
Key = HOME, Value = /Users/abhishekverma
Key = _, Value = /Library/Java/JavaVirtualMachines/
jdk1.8.0_121.jdk/Contents/Home/bin/java

了解上述輸出:輸出是構建的子流程的映射視圖。上述輸出因用戶而異,完全取決於操作係統和用戶。

5. boolean redirectErrorStream():該方法告訴進程構建器是否合並標準錯誤和標準輸出。如果此屬性為 true,則隨後由對象的 start() 方法啟動的子進程生成的任何錯誤輸出都將與標準輸出合並,以便可以使用 Process.getInputStream() 方法讀取兩者。它可以更輕鬆地將錯誤消息與相應的輸出關聯起來。初始值為假。

Syntax: public boolean redirectErrorStream().
Returns: this process builder's redirectErrorStream property.
Exception: NA.

Java


// Java code illustrating redirectErrorStream() method
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating list of commands
        List list = new ArrayList();
        list.add("notepad.exe");
        list.add("xyz.txt");
        // creating the process
        ProcessBuilder build = new ProcessBuilder(list);
        // checking if error stream is redirected
        System.out.println(build.redirectErrorStream());
    }
}

輸出:

false

6. ProcessBuilderredirectErrorStream(boolean redirectErrorStream):此方法設置此流程構建器的redirectErrorStream 屬性。如果此屬性為 true,則隨後由該對象的 start() 方法啟動的子進程生成的任何錯誤輸出都將與標準輸出合並,以便可以使用 Process.getInputStream() 方法讀取兩者。這使得更容易將錯誤消息與相應的輸出關聯起來。初始值為假。

Syntax: public ProcessBuilder redirectErrorStream(boolean redirectErrorStream).
Returns: this process builder.
Exception: NA.

Java


// Java code illustrating redirectErrorStream(boolean
// redirectErrorStream) method
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating list of commands
        List list = new ArrayList();
        list.add("notepad.exe");
        list.add("xyz.txt");
        // creating the process
        ProcessBuilder build = new ProcessBuilder(list);
        // redirecting error stream
        build.redirectErrorStream(true);
        // checking if error stream is redirected
        System.out.println(build.redirectErrorStream());
    }
}

輸出:

true

進程start():此方法使用進程構建器的屬性啟動一個新進程。新進程將在 directory() 指定的工作目錄中調用 command() 指定的命令和參數,進程環境由 environment() 指定。此方法檢查該命令是否是有效的操作係統命令。哪些命令有效取決於係統,但至少該命令必須是非空字符串的非空列表。如果有安全管理器,則調用其 checkExec 方法,並使用該對象的命令數組的第一個組件作為其參數。它可能會導致拋出SecurityException。

Syntax: public Process start().
Returns: a new Process object for managing the subprocess.
Exception: NullPointerException - If an element of the command list is null
IndexOutOfBoundsException - If the command is an empty list (has size 0).
SecurityException - If a security manager exists 
and its checkExec method doesn't allow creation of the subprocess.
IOException - If an I/O error occurs.

Java


// Java code illustrating start() method
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg) throws IOException
    {
        // creating list of commands
        List<String> commands = new ArrayList<String>();
        commands.add("ls"); // command
        commands.add("-l"); // command
        commands.add(
            "/Users/abhishekverma"); // command in Mac OS
        // creating the process
        ProcessBuilder pb = new ProcessBuilder(commands);
        // starting the process
        Process process = pb.start();
        // for reading the output from stream
        BufferedReader stdInput
            = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
    }
}

輸出:

total 0
drwxr-xr-x  10 abhishekverma  staff   340 Jun 20 02:24 AndroidStudioProjects
drwx------@ 22 abhishekverma  staff   748 Jun 20 03:00 Desktop
drwx------@  7 abhishekverma  staff   238 Apr 29 22:03 Documents
drwx------+ 27 abhishekverma  staff   918 Jun 20 03:01 Downloads
drwx------@ 65 abhishekverma  staff  2210 Jun 18 20:48 Library
drwx------+  3 abhishekverma  staff   102 Mar 28 13:08 Movies
drwx------+  4 abhishekverma  staff   136 Apr  8 04:51 Music
drwxr-xr-x   4 abhishekverma  staff   136 Jun 19 15:01 NetBeansProjects
drwx------+  5 abhishekverma  staff   170 Apr 10 09:46 Pictures
drwxr-xr-x+  6 abhishekverma  staff   204 Jun 18 20:45 Public
-rw-r--r--   1 abhishekverma  staff     0 Apr 15 19:23 newreactjs.jsx

ProcessBuilder inheritIO():將子進程標準I/O的源和目標設置為與當前Java進程的源和目標相同。

Syntax: public ProcessBuilder inheritIO().
Returns: this process builder.
Exception: NA.

Java


// Java code illustrating inheritIO() method
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
    public static void main(String[] arg)
        throws IOException, InterruptedException
    {
        ProcessBuilder pb = new ProcessBuilder(
            "echo", "Hello GeeksforGeeks\n"
                        + "This is ProcessBuilder Example");
        pb.inheritIO();
        Process process = pb.start();
        process.waitFor();
    }
}

輸出:

Hello GeeksforGeeks
This is ProcessBuilder Example



相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Java.lang.ProcessBuilder class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。