目录

Process exec(String[] cmdarray, String[] envp, File dir)

描述 (Description)

java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir)方法在具有指定环境和工作目录的单独进程中执行指定的命令和参数。 给定一个字符串数组cmdarray,表示命令行的标记,以及一个字符串envp数组,表示“环境”变量设置,此方法创建一个执行指定命令的新进程。

启动操作系统进程高度依赖于系统。 在许多可能出错的事情中 -

  • 找不到操作系统程序文件。
  • 访问程序文件被拒绝。
  • 工作目录不存在。

在这种情况下,将抛出异常。 异常的确切性质取决于系统,但它始终是IOException的子类。

声明 (Declaration)

以下是java.lang.Runtime.exec()方法的声明

public Process exec(String[] cmdarray, String[] envp, File dir)

参数 (Parameters)

  • cmdarray - 包含要调用的命令及其参数的数组。

  • envp - 字符串数组,其每个元素的格式为name = value的环境变量设置,如果子进程应继承当前进程的环境,则为null。

  • dir - 子进程的工作目录,如果子进程应继承当前进程的工作目录,则返回null。

返回值 (Return Value)

此方法返回一个用于管理子进程的新Process对象

异常 (Exception)

  • SecurityException - 如果存在安全管理器且其checkExec方法不允许创建子进程

  • IOException - 如果发生I/O错误

  • NullPointerException - 如果command为null

  • IndexOutOfBoundsException - 如果cmdarray是一个空数组(长度为0)

例子 (Example)

此示例需要在我们的C:/文件夹中包含名为test.txt文件,其中包含以下内容 -

Hello

以下示例显示了lang.Runtime.exec()方法的用法。

package com.iowiki;
import java.io.File;
public class RuntimeDemo {
   public static void main(String[] args) {
      try {
      // create a new array of 2 strings
      String[] cmdArray = new String[2];
      // first argument is the program we want to open
      cmdArray[0] = "notepad.exe";
      // second argument is a txt file we want to open with notepad
      cmdArray[1] = "test.txt";
      // print a message
      System.out.println("Executing notepad.exe and opening test.txt");
      // create a file which contains the directory of the file needed
      File dir = new File("c:/");
      // create a process and execute cmdArray and currect environment
      Process process = Runtime.getRuntime().exec(cmdArray, null, dir);
      // print another message
      System.out.println("test.txt should now open.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

让我们编译并运行上面的程序,这将产生以下结果 -

Executing notepad.exe and opening test.txt
test.txt should now open.
↑回到顶部↑
WIKI教程 @2018