Methods
Both the Processbuilder.start () and the Runtime.exec () methods are used to create an operating system process (to perform command-line operations) and return an instance of the process subclass that is used to control the status of processes and obtain relevant information.
- The
Runtime.exec(String)
method takes a single command string, the 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 is the arguments.
New Processbuilder ("C:\DoStuff.exe", "-arg1", "-arg2"); // or alternatively list<string> params = java.util.Arrays.asList ("C:\DoStuff.exe", "-arg1", "-arg2"new = Builder.start ()
Examples
def execute = {context = =val Command=Shell (context) var result:try[string]=NULLvar process:process=NULL Try{Val Builder=NewProcessbuilder (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 (NewIllegalmonitorstateexception (S "Exit Code of process is no zero, but: $exitCode")) }Else{result= Success (S "Successfully executed command $command") } }Catch{ CaseE:exception = result =Failure (e)}finally { if(process!=NULL) {Process.destroy ()}} result}
[Scala] Java Execution Shell command