1 public class StreamGobbler extends Thread { 2 3 InputStream is; 4 String type; 5 6 public StreamGobbler(InputStream is, String type) { 7 this.is = is; 8 this.type = type; 9 } 10 11 public void run() { 12 try { 13 InputStreamReader isr = new InputStreamReader(is); 14 BufferedReader br = new BufferedReader(isr); 15 String line = null; 16 while ((line = br.readLine()) != null) { 17 if (type.equals("Error")) { 18 System.out.println("Error :" + line); 19 } else { 20 System.out.println("Debug:" + line); 21 } 22 } 23 } catch (IOException ioe) { 24 ioe.printStackTrace(); 25 } 26 } 27 }
1 private void shell(String cmd) 2 { 3 String[] cmds = { "/bin/sh", "-c", cmd }; 4 Process process; 5 6 try 7 { 8 process = Runtime.getRuntime().exec(cmds); 9 10 StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error"); 11 StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "Output"); 12 errorGobbler.start(); 13 outputGobbler.start(); 14 try 15 { 16 process.waitFor(); 17 } 18 catch (InterruptedException e) 19 { 20 e.printStackTrace(); 21 } 22 } 23 catch (IOException e) 24 { 25 e.printStackTrace(); 26 } 27 }
參數 cmd 為Linux命令。每次只能執行一條命令。
- Java Runtime.exec()注意事項
- 永遠要在調用waitFor()方法之前讀取數據流
- 永遠要先從標准錯誤流中讀取,然后再讀取標准輸出流
2.最好的執行系統命令的方法就是寫個bat文件或是shell腳本。
參考資料:
注意事項參考:
http://blog.csdn.net/flying881114/article/details/6272472
http://blog.csdn.net/westwin/archive/2005/04/22/358377.aspx
http://blog.csdn.net/moreorless/archive/2009/05/15/4182883.aspx
shell腳本參考:
http://blog.csdn.net/HEYUTAO007/archive/2010/06/30/5705499.aspx
