상세 컨텐츠

본문 제목

apache.commons.exec 를 이용한 외부 명령어 실행

프로그래밍/JAVA

by 라제폰 2016. 6. 23. 14:37

본문

* 출처 : http://blog.naver.com/oshnew/10177292282


간혹 JAVA에서 외부 명령어를 실행해야하는 경우가 있다. 

Runtime.getRuntime().exec(command) 로 한땀한땀 만들어주는 것 도 방법이겠지만... 난 지쳤다.;

 

아파치 commons의 라이브러리르 사용하자.

참고 링크 :

1.  http://commons.apache.org/proper/commons-exec/tutorial.html

2. http://blog.sanaulla.info/2010/09/07/execute-external-process-from-within-jvm-using-apache-commons-exec-library/

3. http://blog.naver.com/PostView.nhn?blogId=pluggers&logNo=150049072605

 

1. maven dependency 추가

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

 

2. 샘플코드 : 비동기로 작동

/**
  * async방식으로 외부 명령어 실행
  *  - apachec commons의 exec를 사용
  *  
  * @param command 실행 command
  */
 public void execAsync(CommandLine command) {

  log.info("async exec. command: " + command.toString());

  DefaultExecutor executor = new DefaultExecutor();

  try {
   executor.execute(new CommandLine(command), new DefaultExecuteResultHandler());

  } catch (Exception e) {
   log.error(e.getMessage(), e);
  }

 }

 

2. 샘플코드 : 실행결과를 String으로 받기

 /**
  * 외부 명령 실행 후 결과를 String으로 받음
  * 
  * @param command
  * @return
  * @throws Exception
  */
 public String execAndRtnResult(CommandLine command) throws Exception {

  log.info("execAndRtnResult. command: " + command.toString());

  String rtnStr = "";

  DefaultExecutor executor = new DefaultExecutor();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  PumpStreamHandler streamHandler = new PumpStreamHandler(baos);
  executor.setStreamHandler(streamHandler);

  /* 로컬 테스트시 사용 커멘드
  CommandLine tmp = CommandLine.parse("ipconfig");
  tmp.addArgument("/all");
  */

  try {

   int exitCode = executor.execute(new CommandLine(command));
   rtnStr = baos.toString();

   log.info("exitCode : " + exitCode);
   log.debug("outputStr : " + rtnStr);

  } catch (Exception e) {
   log.warn(e.getMessage(), e); //error로그는 필요시 사용하는 곳 에서 catch후 사용하세요
   throw new Exception(e.getMessage(), e);
  }

  return rtnStr;

 }


관련글 더보기