Command line execution in Java

Run command line command silently on background

String cmd = "ls -al"
CommandLine cmdLine = new CommandLine(cmd);
DefaultExecutor executor = new DefaultExecutor();
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

executor.execute(cmdLine, resultHandler);

resultHandler.waitFor();

int exitValue = resultHandler.getExitValue();
log.info("Command is exiting with value "+ exitValue);

if (exitValue !=0){
    String errorMessage = "Execution of " + cmdLine.toString() + " failed with Exit code " + exitValue;
    log.error(errorMessage, resultHandler.getException());
    throw new CommandLineExecutorException(errorMessage, resultHandler.getException());
}

Run command line command and use output as inputstream for further processing


Runtime rt = Runtime.getRuntime();
String command = "myTool -a abc -t xyz";

Process  cmdProcess = rt.exec(command);

InputStream processOut = cmdProcess.getInputStream();

MyDataStructure<Item> myItems = covertInputToItem(processOut); 

try {
    int exitVal = bedToolsProcess.waitFor();
    
    if (exitVal != 0) {
        throw new IOException("Exec of: " + bedtools_cmd + " failed " + exitVal);
    }
} catch (InterruptedException e) {
    bedToolsProcess.destroy();
    throw new IOException(e);
}