源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java执行Linux命令的方法

  • 时间:2022-07-14 15:29 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java执行Linux命令的方法
本文实例讲述了java执行Linux命令的方法。分享给大家供大家参考。具体实现方法如下:
[u]复制代码[/u] 代码如下:
public class StreamGobbler extends Thread {            InputStream is;      String type;        public StreamGobbler(InputStream is, String type) {          this.is = is;          this.type = type;      }        public void run() {          try {              InputStreamReader isr = new InputStreamReader(is);              BufferedReader br = new BufferedReader(isr);              String line = null;              while ((line = br.readLine()) != null) {                  if (type.equals("Error")) {                      System.out.println("Error   :" + line);                  } else {                      System.out.println("Debug:" + line);                  }              }          } catch (IOException ioe) {              ioe.printStackTrace();          }      }  }  private void shell(String cmd) {         String[] cmds = { "/bin/sh", "-c", cmd };         Process process;         try         {             process = Runtime.getRuntime().exec(cmds);             StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error");             StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "Output");             errorGobbler.start();             outputGobbler.start();             try             {                 process.waitFor();             }             catch (InterruptedException e)             {                 e.printStackTrace();             }         }         catch (IOException e)         {             e.printStackTrace();         } }
其中参数 cmd 为Linux命令。每次只能执行一条命令。 [b]1.Java Runtime.exec()注意事项:[/b] ① 永远要在调用waitFor()方法之前读取数据流 ② 永远要先从标准错误流中读取,然后再读取标准输出流 [b]2.最好的执行系统命令的方法就是写个bat文件或是shell脚本。[/b] 希望本文所述对大家的Java程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部