这里以调用windows的cmd为例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RuntimeTest
{
public static void main(String[] args)
{
invokeOuterApplication();
}
private static boolean invokeOuterApplication()
{
boolean issuccess = false;
Runtime runtime = Runtime.getRuntime();
int exitVal = 1;
Process process = null;
try
{
String[] args = {"C:\\Windows\\System32\\cmd.exe","/c ipconfig -all"};
process = runtime.exec("cmd /c netstat -an");
/*上传文件的进程必须与主进程同步,因为主进程要知道文件是否上传成功后才可以返回,这样就必须调用waitFor()方法,
*而Process的waitFor()方法是可能阻塞线程的执行的,如果waitFor()方法会写缓存,包括标准输入缓存和标准错误缓存,如果
*这两个缓存写满了,而这两个又没有被读取使用掉,那么waitFor()方法就会阻塞,等待缓存被读取,所以要加下面这一段来
*保证在任何时候缓存都被正确读取,这样才可以保证waitFor()方法顺畅的执行完毕,而不至于应阻塞进入死锁。
*/
final StringBuilder errorInfo = new StringBuilder();
final BufferedReader inBr = new BufferedReader(new InputStreamReader(process.getInputStream()));
final BufferedReader errBr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
new Thread()
{
public void run()
{
String infoLine = null;
try {
while ((infoLine = inBr.readLine()) != null)
{
System.out.println(infoLine);
}
inBr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
new Thread()
{
public void run()
{
String errLine = null;
try {
while ((errLine = errBr.readLine()) != null)
{
errorInfo.append(errLine);
}
errBr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
exitVal = process.waitFor();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
process.getInputStream().close();
process.getErrorStream().close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (exitVal == 0)
{
issuccess = true;
}
return issuccess;
}
}
启动的第一个线程可以打印出应用程序的输出,同样如果有需要可以对应用程序输出的内容进行相应的处理,只要加上自己的处理代码就可以了
以上这个程序可以在java的控制台显示出和cmd命令行执行ipconfig -all输出的内容一样的内容
这里对/c 参数要做一点说明:
启动 Windows 命令解释器的一个新实例
CMD [/A|/U] [/Q] [/D] [/E:ON|/E:OFF] [/F:ON|/F:OFF] [/V:ON|/V:OFF] [[/S] [/C|/K] string]
/C 执行字符串指定的命令然后终止
/K 执行字符串指定的命令但保留
/S 修改/C 或/K 之后的字符串处理(见下)
/Q 关闭回显
/D 禁止从注册表执行 AutoRun 命令(见下)
/A 使向管道或文件的内部命令输出成为 ANSI
/U 使向管道或文件的内部命令输出成为 Unicode
/T:fg 设置前台/背景颜色(详细信息见 COLOR /?)
/E:ON 启用命令扩展(见下)
/E:OFF 禁用命令扩展(见下)
/F:ON 启用文件和目录名完成字符(见下)
/F:OFF 禁用文件和目录名完成字符(见下)
/V:ON 使用! 作为分隔符启用延迟的环境变量
扩展。例如,/V:ON 会允许 !var! 在执行时扩展变量 var。var 语法会在输入时扩展变量,这与在一个 FOR循环内不同。
/V:OFF 禁用延迟的环境扩展。