• [Java] Java执行Shell命令


    Methods

    ProcessBuilder.start() 和 Runtime.exec() 方法都被用来创建一个操作系统进程(执行命令行操作),并返回 Process 子类的一个实例,该实例可用来控制进程状态并获得相关信息。 

         Process process = Runtime.getRuntime().exec("C:DoStuff.exe -arg1 -arg2");
    • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments.
    ProcessBuilder b = new ProcessBuilder("C:DoStuff.exe", "-arg1", "-arg2");
    //or alternatively
    List<String> params = java.util.Arrays.asList("C:DoStuff.exe", "-arg1", "-arg2");
    ProcessBuilder b = new ProcessBuilder(params);
    Process process = builder.start()

    Examples 

    def execute = { context =>
          val command = shell(context)
          var result:Try[String]  = null
          var process:Process = null
          try {
            val builder = new ProcessBuilder(scala.collection.JavaConversions.seqAsJavaList(command))
            builder.redirectOutput(ProcessBuilder.Redirect.INHERIT)
            builder.redirectError(ProcessBuilder.Redirect.INHERIT)
            process = builder.start()
            process.waitFor()
            val exitCode = process.exitValue()
            if(exitCode != 0 ) {
              result = Failure(new IllegalMonitorStateException(s"Exit code of process is not zero, but: $exitCode"))
            }else {
              result = Success(s"Successfully executed command $command")
            }
          }catch{
            case e: Exception => result = Failure(e)
          } finally {
            if(process!=null) {
              process.destroy()
            }
          }
          result
        }
  • 相关阅读:
    加壳技术
    1002 ( A + B Problem II )
    1000 ( A + B Problem )
    1001 ( Sum Problem )
    背单词Delphi版
    覆盖Form.WndProc来响应消息
    覆盖Dispatch响应消息
    美丽人生论坛看贴工具delphi版
    TWebBrowser组件在DELPHI中POST数据和取得网页源文件
    读淘宝商品描述页源码delphi版
  • 原文地址:https://www.cnblogs.com/qingwen/p/5161166.html
Copyright © 2020-2023  润新知