目录

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

描述 (Description)

java.lang.Runtime.exec(String command, String[] envp, File dir)方法在具有指定环境和工作目录的单独进程中执行指定的字符串命令。 这是一种方便的方法。 调用exec(command,envp,dir)的形式与调用exec(cmdarray,envp,dir)完全相同,其中cmdarray是命令中所有标记的数组。

更准确地说,命令字符串使用由调用new StringTokenizer(命令)创建的StringTokenizer分解为标记,而不进一步修改字符类别。 然后,由标记器生成的标记以相同的顺序放置在新的字符串数组cmdarray中。

声明 (Declaration)

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

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

参数 (Parameters)

  • command - 指定的系统命令。

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

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

返回值 (Return Value)

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

异常 (Exception)

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

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

  • NullPointerException - 如果command为null,或者envp的某个元素为null

  • IllegalArgumentException - 如果命令为空

例子 (Example)

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

package com.iowiki;
import java.io.File;
public class RuntimeDemo {
   public static void main(String[] args) {
      try {
      // print a message
      System.out.println("Executing notepad.exe...");
      // create a file with the working directory we wish
      File dir = new File("C:/");
      // create a process and execute notepad.exe and currect environment
      Process process = Runtime.getRuntime().exec("notepad.exe", null, dir);
      // print another message
      System.out.println("Notepad should now open.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Executing notepad.exe...
Notepad should now open.
↑回到顶部↑
WIKI教程 @2018