当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。