使用到Process和Runtime两个类,返回值经过Process类的getInputStream()方法获取java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ReadCmdLine { public static void main(String args[]) { Process process = null; List<String> processList = new ArrayList<String>(); try { process = Runtime.getRuntime().exec("df -hl"); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; while ((line = input.readLine()) != null) { processList.add(line); } input.close(); } catch (IOException e) { e.printStackTrace(); } for (String line : processList) { System.out.println(line); } } }
一般咱们在第一步执行完调用后,须要知道命令是否执行完毕,则须要经过wait for()来实现git
Process proc = Runtime.getRuntime().exec("xx.exe"); try { if (proc.waitFor() != 0) { System.err.println("exit value = " + proc.exitValue()); } } catch (InterruptedException e) { System.err.println(e); }
proc.waitfor()的返回结果若是不为0,则执行异常,为0,则命令执行正确。github
缘由:因为 JVM 提供标准输入和输出流的缓冲区大小是十分有限,很快的读入或者输出流将会致使进程阻塞或者锁死。shell
解决方法:再调用两个线程分别输出标准输出流和标准错误流,这样就能够解决标准输出和错误流缓冲区限制而致使的阻塞和锁死状态了。函数
解决线程阻塞和锁死的类以下:this
class RunThread extends Thread { InputStream is; String type; RunThread(InputStream is, String printType) { this.is = is; this.printType = printType; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) System.out.println(PrintType + ">" + line); } catch (IOException ioe) { ioe.printStackTrace(); } } }
执行外部命令的主函数:spa
public class Runpro { public void main(String arg[]){ try { System.out.println("cmd start"); Process p = Runtime.getRuntime().exec("pwd"); //调用Linux的相关命令 new RunThread(p.getInputStream(), "INFO").start(); new RunThread(p.getErrorStream(),"ERR").start(); int value = p.waitFor(); if(value == 0) System.out.println("complete"); else System.out.println("failuer"); } catch (IOException e) { e.printStackTrace(); } } }