Arquivo da tag: comandos

Executor de comandos em Java

/**
 *
 * @author joaosavio
 */
public class CommandExecutor {
    /**
     * Executes a command line
     * @param line
     * @return the exit code
     */
    public int execute(String line) {
        return execute(line, null);
    }
     
    /**
     * Executes a command line
     * @param line
     * @param expectedExitCode
     * @return the exit code
     */
    public int execute(String line, Integer expectedExitCode) {
        CommandLine commandLine = CommandLine.parse(line);
        Executor executor = new DefaultExecutor();
       
        if (expectedExitCode != null) {
            executor.setExitValue(expectedExitCode); 
        }
        try {
            int exitValue = executor.execute(commandLine);
            return exitValue;
        } catch (ExecuteException e) {
            // handle the exception
        } catch (IOException e) {
            // handle the exception
        } 
    }
}

No pom.xml adicione:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.1</version>
</dependency>