public static String exec ( final String [ ] cmds , final long timeout ) { try { final Process process = new ProcessBuilder ( cmds ) . redirectErrorStream ( true ) . start ( ) ; final StringWriter writer = new StringWriter ( ) ; new Thread ( ( ) -> { try { IOUtils . copy ( process . getInputStream ( ) , writer , "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Reads input stream failed: " + e . getMessage ( ) ) ; } } ) . start ( ) ; if ( ! process . waitFor ( timeout , TimeUnit . MILLISECONDS ) ) { LOGGER . log ( Level . WARN , "Executes commands [" + Arrays . toString ( cmds ) + "] timeout" ) ; process . destroy ( ) ; } return writer . toString ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Executes commands [" + Arrays . toString ( cmds ) + "] failed" , e ) ; return null ; } }
Executes the specified commands with the specified timeout .