java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir)%uA0方法执行在指定环境和工作目录的独立进程中指定的命令和参数。字符串给定一个数组cmdarray,代表一个命令行标记和一个字符串数组envp,代表“环境”变量设置,此方法创建要在其中执行指定的命令新的进程。
启动操作系统的过程是高度依赖于系统的。在众多的事情都可能出错是:
-
未找到操作系统程序文件。
-
访问该程序文件被拒绝。
-
工作目录不存在。
在这种情况下,一个异常将被抛出。异常的确切性质取决于系统,但它永远是IOException异常的子类。
声明
以下是java.lang.Runtime.exec()方法的声明
public Process exec(String[] cmdarray, String[] envp, File dir)
参数
-
cmdarray%uA0-- 调用及其参数包含命令数组。
-
envp%uA0-- 字符串数组,其中的每个元素都有其格式为name = value设置环境变量,则返回null,如果子进程应该继承当前进程的环境。
-
dir%uA0-- 子进程的工作目录,或null,如果子进程应该继承当前进程的工作目录。
返回值
该方法返回一个新的Process对象,用于管理子进程
异常
-
SecurityException%uA0-- 如果安全管理器存在,并且其checkExec方法不允许创建子进程
-
IOException%uA0-- 如果发生I/ O错误
-
NullPointerException%uA0--如果命令为空
-
IndexOutOfBoundsException%uA0--%uA0如果cmdarray是一个空数组(长度为0)
例子
此示例要求名为c:/test.txt在/文件夹C:/ folder :包含以下内容:
Hello
下面的例子显示lang.Runtime.exec()方法的使用。
package com.yiibai 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.