티스토리 뷰

**윈도우 환경에서**

 

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를 잘 출력하는 것을 알 수 있다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함