노무현 대통령 배너

'commons'에 해당되는 글 1건

  1. 2008/12/29 Apache Commons CLI로 명령줄 인터페이스 구현하기 (2)
윈도우를 쓰다보니 명령줄은 잘 안쓰지만 시스템을 연동할때는 명령줄 인터페이스가 필요할때가 많습니다. Ant와 같은 명령줄 인터페이스를 쉽게 만들 수 있게 해주는 오픈소스가 Commons CLI 입니다.

Commons CLI를 이용해서 명령줄 인터페이스를 만드는 과정은 명령줄 옵션 정의, 옵션 값 파싱, 옵션에 따르는 처리를 정의하는것으로 이루어 집니다.

1.명령줄 옵션 정의
Options options = new Options();
options.addOption("t", false, "display current time");
options.addOption("d", true, "get directory");

Options 객체는 Option 객체를 갖으며 각 Option 객체는 옵션 플래그, 옵션이 값을 가지는지 여부를 나타내는 boolean 값, 옵션에 대한 설명으로 만들어 집니다.

위에서 정의한 옵션은 명령줄에서 --t  --d C:\download 와 같이 줄 수가 있습니다.

2.옵션값 파싱
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);

옵션값을 String[]인 args로 받았다면 CommandLineParser를 이용해서 옵션값을 파싱하는게 가능합니다. 파싱 결과는 CommandLine 객체로 구해집니다.

3.옵션에 대한 처리
            if(cmd.hasOption("d")) {
                System.out.println("d option value: "+cmd.getOptionValue("d"));
            }

옵션이 주어졋는지 여부는 CommandLine 객체의 hasOption() 메소드로 알 수 있습니다. 옵션이 주어진 경우에는 getOptionValue로 실제 값을 구할 수 있습니다.

이 외에도 옵션에 대한 도움말도 처리해야 하는데 HelpFormatter를 이용하면 간단히 깔끔하게 도움말을 출력할 수 있습니다.
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp( "sampleCLI", options );

위 처리에 대한 결과는 다음과 같습니다.
usage: sampleCLI
 -cd,--directory <arg>   get current directory
 -d <arg>                get directory
 -p <package>            get package
 -t                      display current time






크리에이티브 커먼즈 라이선스
Creative Commons License