---
title: "Java Runtime.exec()注意事项 ."
author: "robinjoe"
date: "2011-10-19T11:49:39Z"
tags: ["java Api"]
categories: ["编程语言"]
slug: "java-runtime-exec"
draft: false
lastmod: "2011-10-19T11:49:39Z"
id: 1201390
url: "https://robinjoe.iteye.com/blog/1201390"
---

**0. Runtime.exec()用来执行外部程序或命令**

 

 

**1. Runtime.exec() 有四种调用方法**

    * public Process exec(String command);  
    * public Process exec(String \[] cmdArray);  
    * public Process exec(String command, String \[] envp);  
    * public Process exec(String \[] cmdArray, String \[] envp);

 

 

**2. 得到程序执行返回值, 0为success**

需要用waitFor()函数，比如

Process p = Runtime.getRuntime().exec("javac");

(处理.....)  
int exitVal = p.waitFor();

 

**3. 得到程序执行的结果或错误信息**

需要用BufferedInputStream 和 BufferReader来得到，否则程序会hang

比如得到错误信息用p.getErrorStream()，然后输出即可:

BufferedInputStream in = new BufferedInputStream(p.getErrorStream());  
BufferedReader br = new BufferedReader(new InputStreamReader(in));

 

 

**4. Runtime.exec() 不等同于直接执行command line命令！**

啊，我算是在这里吃了苦头了。Runtime.exec()很有局限性，对有些命令不能直接把command line里的内容当作String参数传给exec().

比如重定向等命令。举个例子:

javap -l xxx &gt; output.txt

这时要用到exec的第二种重载，即input 参数为String\[]:

Process p = Runtime.getRuntime().exec(new String\[]{"/bin/sh","-c","javap -l xxx &gt; output.txt"});

转自：[http://blog.csdn.net/flying881114/article/details/6272472](http://blog.csdn.net/flying881114/article/details/6272472)