java执行Linux命令

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

java执行linux命令 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 try15 {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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航