Process exec(String[] cmdarray)

描述 (Description)

java.lang.Runtime.exec(String[] cmdarray)方法在单独的进程中执行指定的命令和参数。 这是一种方便的方法。 调用exec(cmdarray)形式的行为与调用exec(cmdarray,null,null)完全相同。

声明 (Declaration)

以下是java.lang.Runtime.exec()方法的声明public Process exec(String[] cmdarray)

参数 (Parameters)

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

返回值 (Return Value)

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

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

IOException - 如果发生I/O错误

NullPointerException - 如果command为null

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

例子 (Example)

此示例需要在CLASSPATH中使用名为example.txt的文件,其中包含以下内容 -Hello World!

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

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] = "example.txt";

// print a message

System.out.println("Executing notepad.exe and opening example.txt");

// create a process and execute cmdArray

Process process = Runtime.getRuntime().exec(cmdArray);

// print another message

System.out.println("example.txt should now open.");

} catch (Exception ex) {

ex.printStackTrace();

}

}

}

让我们编译并运行上面的程序,这将产生以下结果 -Executing notepad.exe and opening example.txt

example.txt should now open.

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐