티스토리 뷰
**윈도우 환경에서**
JAVA 프로그램을 이용해서 외부 프로그램 실행을 해야할 경우가 있어서 ProcessBuilder를 이용해서
테스트를 해봤는데 cmd를 띄웠을 때 초기 메세지만 뜨고 명령어 인식이 안되었다.
public void Cmd() throws IOException {
String[] cmd = new String[] {"cmd", "dir"};
Process process = null;
String str = null;
try {
process = new ProcessBuilder(cmd).start();
BufferedReader stdOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((str = stdOut.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
▶ 결과
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
▶ 해결방법
String[] cmd로 명령어를 던져주는 부분에 "cmd" 뒷부분에 "/c"를 넣어주면 dir에 대한 수행 결과를 보여준다.
String[] cmd = new String[] {"cmd", "/c", "dir"};

**리눅스 환경에서**
리눅스에서는 cmd.exe를 실행할 필요없이 바로 명령어 실행이 가능하다.
그러나 생성자부분 String 배열 형태의 나열 방식이 먹히지 않아서
List를 파라미터로 주어서 해결했다.
public void Cmd() throws IOException {
List cmdList = new ArrayList();
cmdList.add("pwd");
Process process = null;
String str = null;
try {
process = new ProcessBuilder(cmdList).start();
BufferedReader stdOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((str = stdOut.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
▶ 결과

pwd 로 path를 잘 출력하는 것을 알 수 있다.
'JAVA' 카테고리의 다른 글
Java로 외부 프로그램 실행(명령어 두 개 실행) (0) | 2019.04.10 |
---|---|
Java로 외부프로그램 실행 (리눅스 cd 명령어 적용하기) (0) | 2019.04.10 |