일단은 프로그래머 나부랭이

java에서 shell cmd 수행하는 방법 본문

Java

java에서 shell cmd 수행하는 방법

하필이면 도대체가 2020. 11. 24. 14:59

Java에서 shell cmd를 수행할 필요가 있었다.
아래와 같이 구현은 했는데, 여러모로 쓸모가 많을 것 같아서 메모를 남겨둔다.

 

class ShellExecute{
	Runtime runtime = Runtime.getRuntime();
	String [] exec = new String[3];
	
	ShellExecute() {
    	// 아래의 명령어를 생략하면 일부 cmd만 실행 가능
		this.exec[0] = "/bin/bash";
		this.exec[1] = "-c";
	}
	
    // cmd 수행
	public void shellCmd(String command) throws Exception {
		exec[2] = command;
		Process process = runtime.exec(exec);
		process.waitFor();
	}
	
    // cat 등으로 파일의 내용을 확인 할 때 사용
	public String openFile(String command) throws Exception {
		exec[2] = command;
		Process process = runtime.exec(exec);
		process.waitFor();

		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);

		return br.readLine();
	}
}

 


Comments