输出命令调用之后的返回值:
public static void main(String[] args) {
try {
String[] cmd = new String[]{"/bin/sh","-c", "cmd"};
Process ps = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
System.out.println(result);//输出返回值
} catch (IOException e) {
e.printStackTrace();
}
}
某些程序可能不支持,则需要使用Process.exitValue()来判断程序的运行状态是否成功。
public static void main(String[] args) throws Exception {
try {
String[] cmd = new String[]{"/bin/sh","-c", "cmd"};
Process ps = Runtime.getRuntime().exec(cmd);
ps.waitFor();//阻塞线程,等待数据返回
int i = ps.exitValue();//true is 0 ,false is 1
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
}
}
如果不使用Process.waitFor()来将线程阻塞,而直接使用Process.exitValue()时,因为exitValue()采用非阻塞的方式返回,如果没有立即拿到返回值,则抛出异常。
Process.waitFor()当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。
当使用Process.waitFor()时可能会导致主线程阻塞,子进程在运行命令时一直没有返回,或者缓冲区已满,需要注意及时清空缓冲区。
在调用waitFor() 的时候,Process需要向主线程汇报运行状况,所以要注意清空缓存区,即InputStream和ErrorStream。
假设该程序不断在向标准输出流和标准错误流写数据,而JVM不读取的话,当缓冲区满之后将无法继续写入数据,最终造成阻塞在waitFor()这里。方法多数是开两个线程在waitFor()命令之前读出窗口的标准输出缓冲区和标准错误流的内容。代码如下:
Runtime rt = Runtime.getRuntime();
String command = "cmd";
try {
p = rt.exec(command ,null,new File("filePath")); //获取进程的标准输入流
final InputStream is1 = p.getInputStream(); //获取进程的错误流
final InputStream is2 = p.getErrorStream(); //启动两个线程,一个线程负责读标准输出流,另一个负责读标准错误流
new Thread() {
public void run() {
BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
try {
String line1 = null;
while ((line1 = br1.readLine()) != null) {
if (line1 != null){}
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
is1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
try {
String line2 = null ;
while ((line2 = br2.readLine()) != null ) {
if (line2 != null){}
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
is2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
p.waitFor();
p.destroy();
System.out.println("我想被打印...");
} catch (Exception e) {
try{
p.getErrorStream().close();
p.getInputStream().close();
p.getOutputStream().close();
}
catch(Exception ee){}
}
}
Q.E.D.