[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
}
上一篇:AC自动机+全概率+记忆化DP UVA 11468 Substring


下一篇:[转]Git for windows 下vim解决中文乱码的有关问题