Methods
ProcessBuilder.start() 和 Runtime.exec() 方法都被用来创建一个操作系统进程(执行命令行操作),并返回 Process 子类的一个实例,该实例可用来控制进程状态并获得相关信息。
- The
Runtime.exec(String)
method takes a single command string that it splits into a command and a sequence of arguments.
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 }
时间: 2024-11-07 09:49:13