1. Runtime.getRuntime().exec()能做什么?
1)调用外部程序
// 调用的是javac.exe小程序
Runtime.getRuntime().exec("javac");
2)调用外部程序的某个指令
// 调用的是cmd.exe中的dir指令
Runtime.getRuntime().exec("cmd /c dir");
3)调用外部的批处理文件(.bat)
// 调用的是目录【D:\\test】下的【test.bat】脚本
runtime.exec("cmd /c test.bat", null, new File("D:\\test"));
2. "cmd /c dir"中的/c是啥意思?
cmd /c 执行结束后,关闭cmd进程.
cmd /k 执行结束后,不关闭cmd后台进程.
3. Runtime提供了几个exec()方法,里面的参数都是啥意思?
public Process exec(String command);
public Process exec(String command, String[] envp);
public Process exec(String command, String[] envp, File dir);
public Process exec(String cmdarray[]);
public Process exec(String[] cmdarray, String[] envp);
public Process exec(String[] cmdarray, String[] envp, File dir);
a. command
一个命令。可包含命令和参数。
b. envp
一组环境变量的设置。
格式:name=value 或 null.
c. dir
子进程的工作目录。
e. cmdarray
包含多个命令的数组。其中每个命令可包含命令和参数。
4. 一个比较完整的使用示例,见下面代码。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.junit.Test;
public class Demo {
@Test
public void testName() throws Exception {
// 调用命令
Runtime runtime = Runtime.getRuntime();
Process process = null;
process = runtime.exec("javac"); // 用法1:调用一个外部程序
// process = runtime.exec("cmd /c dir"); // 用法2:调用一个指令(可包含参数)
// process = runtime.exec("cmd /c test.bat", null, new File("D:\\test")); // 用法3:调用一个.bat文件
// 存放要输出的行数据
String line = null;
// 输出返回的报错信息
System.out.println("=================ErrorStream===================");
BufferedReader inErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = inErr.readLine()) != null) {
System.out.println(line);
}
// 输出正常的返回信息
System.out.println("=================InputStream===================");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// 获取退出码
int exitVal = process.waitFor(); // 等待进程运行结束
System.out.println("exitVal = " + exitVal);
}
}