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
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章