자바

쉘, 커멘드 명령어 실행 방법

UGO 2021. 4. 28. 17:10

apache common 의 라이브러리를 이용하면 아주 쉽게 쉘이나, cmd 에서의 명령어 수행이 가능하다.

 

1. pom.xml 에 추가

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

 

 

2. 메소드 구현

public void runPdf2htmlEx(String fileNm) throws Exception {
    String[] command = {html2pdfEX, fileNm};

    DefaultExecutor executor = new DefaultExecutor();
    CommandLine cmdLine = CommandLine.parse(command[0]);
    for (int i = 1, n = command.length; i < n; i++) {
        cmdLine.addArgument(command[i]);
    }
    log.debug("cmdLine : " + cmdLine.toString());

    // 동시 실행

    executor.execute(new CommandLine(cmdLine), new DefaultExecuteResultHandler());

    // 개별로 실행 ( 하나가 끝나야 다음거를 수행함)

    // executor.execute(cmdLine);
    executor.setExitValue(1);

}