Java에서 cmd 명령어를 실행하고 결과를 받을 수 있습니다. 실행 중인 프로세스가 무엇인지, IP가 무엇인지 등을 윈도우 cmd 명령어를 호출하여 체크할 수 있습니다.
JAVA에서 명령어 호출 및 결과를 읽는 방법에 대해서 알아보겠습니다.
1. Java에서 cmd 명령어 실행
Java의 Runtime
클래스를 이용하여 아래와 같이 명령어를 실행할 수 있습니다. 윈도우 명령어를 입력할 때는 앞에 cmd -c
를 붙여야 합니다.
예를 들어, ipconfig
를 실행하고 싶을 때는 cmd /c ipconfig
처럼 입력합니다.
Runtime.getRuntime().exec("cmd /c " + cmd);
2. cmd 실행 결과 받기
Runtime.exec()
로 명령어를 호출하면 결과가 Process 객체로 리턴됩니다.
다음과 같이 Process 객체로부터 결과를 읽을 수 있습니다. Process로부터 InputStreamReader를 가져와서 문자열을 읽습니다.
Process process = Runtime.getRuntime().exec("cmd /c " + cmd);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
StringBuffer sb = new StringBuffer();
sb.append(cmd);
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
String result = sb.toString();
3. Sample code
아래와 같이 함수로 만들어두면 사용하기 좋습니다. 인자로 명령어를 전달하면 그 결과가 문자열로 리턴됩니다.
public String execCmd(String cmd) {
try {
Process process = Runtime.getRuntime().exec("cmd /c " + cmd);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
StringBuffer sb = new StringBuffer();
sb.append(cmd);
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Loading script...
Related Posts
- java와 javac의 차이점
- Java - 자바(JDK) 버전 확인 방법 (터미널, cmd 명령어)
- NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper 에러
- Java - HttpClient에 Timeout 적용
- IntelliJ에서 Java 실행 파일 배포 (Export Runnable JAR)
- Java - JAR 디컴파일 방법 (JD-GUI, JD-CLI)
- Java - 키보드, 마우스 이벤트 받기 (이벤트 후킹)
- Java에서 윈도우 cmd 명령어 실행 및 결과 출력
- Java - Selenium 드라이버 자동 설치 방법
- Java - ".class" 파일을 Java 파일로 디컴파일하는 방법 (jd-cli decompiler)
- Gradle로 Java 빌드하는 방법