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              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命令。每次只能执行一条命令。

  1. 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

posted @ 2014-11-20 13:57  晨星坠  阅读(15865)  评论(0编辑  收藏  举报