在知乎上有个知友提问
Java Runtime.exec(String[] cmdarray)与Java Runtime.exec(String cmdarray)区别,自己问了问度娘,大概得出的区别
cmdarray -- 数组,包含所调用命令及其参数.
这需要一个文件名为example.txt在我们的CLASSPATH中包含以下内容:
Hello World!
下面的例子说明了如何使用lang.Runtime.exec()方法。
package com.yiibai;
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 and currect environment
Process process = Runtime.getRuntime().exec(cmdArray,null);
// 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.
而Java Runtime.exec(String cmdarray)直接执行cmd命令即可。