Runtime 클래스와 Process 클래스 이용하여 커맨트 실행하고 결과 확인하기
도스 상의 cmd를 호출하고 해당 결과값을 화면에 출력하는 프로그램
Runtime rt = Runtime.getRuntime();
=> 생성자 존재 안함
Process p = rt.exec("c:\\test.cmd");
=> 프로세스 실행
실행 후 결과값이 나오는데 딜레이가 걸리므로
결과 출력은 thread를 돌림
ExcuteCmd 자체가 Runnable 을 implement 하게 하고
이를 Thread로 돌림
package executecmd;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 도스 명령어를 실행시키는 Java 프로그램
* Process 를 통해 실행 후 결과값은 Thread를 통해 출력해줌
* Cmd 실행 결과가 나오는 시점은 바로는 아닐꺼 같음
* c:\\test.cmd 내용
* 텍스트 파일 열고 ipconfig 명령어만 입력하였음.
*
* @author seungkyu.lee
* @since 2010.11.19
*/
public class ExecuteCmd implements Runnable {
InputStream is = null;
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
Process proc = rt.exec("c:\\test.cmd");
Thread errPrint = new Thread( new ExecuteCmd( proc.getErrorStream() ) );
Thread successPrint = new Thread( new ExecuteCmd( proc.getInputStream() ) );
errPrint.start();
successPrint.start();
if( proc.waitFor() == 0 ) {
System.out.println( "Ok..." );
} else {
System.out.println( "Error..." );
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public ExecuteCmd() {}
public ExecuteCmd( InputStream is ) {
this.is = is;
}
public void run() {
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
String strLine = new String();
try {
while( ( strLine = br.readLine() ) != null ) {
System.out.println( strLine );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if( br != null ) {
br.close();
}
if( is != null ) {
is.close();
}
} catch( Exception e ) {
e.printStackTrace();
}
}
}
}