服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java中调用外部命令

java中调用外部命令

public class execcommond{

public execcommond(){}

/**

  * 执行一条命令

  * @param execstr string 命令字符串

  * @return string 执行命令错误时的信息。

  */

 public static string  exec(string execstr) {

    runtime runtime = runtime.getruntime(); 取得当前运行期对象

    string   outinfo=""; //执行错误的输出信息

    try {

          string[] args = new string[] {"sh", "-c", execstr};//执行linux下的命令

              //执行windows下的命令

//                   string[] args = new string[] {"cmd", "-c", execstr};

      process proc = runtime.exec(args); //启动另一个进程来执行命令

      inputstream in = proc.geterrorstream();//得到错误信息输出。

      bufferedreader br = new bufferedreader(new inputstreamreader(in));

      string line = "";

      while ( (line = br.readline())

             != null) {

        outinfo = outinfo + line + "/n";

        system.out.println(outinfo);

      }

      // 检查命令是否失败。

 

      try {

        if (proc.waitfor() != 0) {

          system.err.println("exit value = " +

                             proc.exitvalue());

        }

      }

      catch (interruptedexception e) {

        system.err.print(e);

        e.printstacktrace();

      }

    }

    catch (ioexception e) {

      flag = false;

      system.out.println("exec error: " + e.getmessage());

      e.printstacktrace();

    }

    finally {

      return outinfo;

    }

  }

}

扫描关注微信公众号