当前位置: 移动技术网 > IT编程>开发语言>Java > Java执行cmd命令两种实现方法解析

Java执行cmd命令两种实现方法解析

2020年07月29日  | 移动技术网IT编程  | 我要评论

一般java在执行cmd命令时,通常是使用runtime.getruntime.exec(command)来执行的,这个方法有两种细节要注意:

1.一般执行方法,代码如下,这种方法有时执行exe时会卡在那里。

//一般的执行方法,有时执行exe会卡在那  stmt要执行的命令
  public static void executive(string stmt) throws ioexception, interruptedexception {
    runtime runtime = runtime.getruntime(); //获取runtime实例
    //执行命令
    try {
      string[] command = {"cmd", "/c", stmt};
      process process = runtime.exec(command);
      // 标准输入流(必须写在 waitfor 之前)
      string instr = consumeinputstream(process.getinputstream());
      // 标准错误流(必须写在 waitfor 之前)
      string errstr = consumeinputstream(process.geterrorstream());
      new processclearstream(process.getinputstream(), "info").start();
      new processclearstream(process.geterrorstream(), "error").start();
      int proc = process.waitfor();
      inputstream errorstream = process.geterrorstream(); //若有错误信息则输出
      if (proc == 0) {
        system.out.println("执行成功");
      } else {
        system.out.println("执行失败" + errstr);
      }
    } catch (ioexception | interruptedexception e) {
      e.printstacktrace();
    }
  }

  /**
   * 消费inputstream,并返回
   */
  public static string consumeinputstream(inputstream is) throws ioexception {
    bufferedreader br = new bufferedreader(new inputstreamreader(is,"gbk"));
    string s;
    stringbuilder sb = new stringbuilder();
    while ((s = br.readline()) != null) {
      system.out.println(s);
      sb.append(s);
    }
    return sb.tostring();
  }

2.第二种方法是先生成一个缓存文件,用来缓存执行过程中输出的信息,这样在执行命令的时候不会卡。代码如下:

//这个方法比第一个好,执行时不会卡 stmt要执行的命令
  public static void aaa(string stam){
    bufferedreader br = null;
    try {
      file file = new file("d:\\daemontmp");
      file tmpfile = new file("d:\\daemontmp\\temp.tmp");//新建一个用来存储结果的缓存文件
      if (!file.exists()){
        file.mkdirs();
      }
      if(!tmpfile.exists()) {
        tmpfile.createnewfile();
      }
      processbuilder pb = new processbuilder().command("cmd.exe", "/c", stam).inheritio();
      pb.redirecterrorstream(true);//这里是把控制台中的红字变成了黑字,用通常的方法其实获取不到,控制台的结果是pb.start()方法内部输出的。
      pb.redirectoutput(tmpfile);//把执行结果输出。
      pb.start().waitfor();//等待语句执行完成,否则可能会读不到结果。
      inputstream in = new fileinputstream(tmpfile);
      br= new bufferedreader(new inputstreamreader(in));
      string line = null;
      while((line = br.readline()) != null) {
        system.out.println(line);
      }
      br.close();
      br = null;
      tmpfile.delete();//卸磨杀驴。
      system.out.println("执行完成");
    } catch (exception e) {
      e.printstacktrace();
    } finally {
      if(br != null) {
        try {
          br.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网