linux下JAVA调用shell脚本

JAVA调用shell脚本时,如果有大量输出,则用Runtime.exec()方法会很慢,这时应该用ProcessBuilder.start() 方法。搞了一晚上,苍了个天!具体参考原文:https://www.cnblogs.com/qingwen/p/5161166.html


阅读目录


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
    }

猜你喜欢

转载自blog.csdn.net/qq_22339269/article/details/79759554